看看Java中如何定义一个类,然后用来调用的,这个比较简单,直接看代码吧。

 

我发现的类和C++不一样的地方:

1.Java中类定义大括号后没有分号;

2.好像没有 public、private等关键字(我也是跟着一个教程学的,至少刚开始没看到,补充一下后来知道有了写法是,直接 private int num; 这样在变量类型的前面直接加)

3.感觉类里面直接就写函数的实现了,不像C++在.h中进行定义,在.cpp中进行实现。

 

一个最基本的类,被外部调用:

package a.b;
class Human
{
    void breath()
    {
        System.out.println("hu.....hu.....");
    }
    int height;
}
public class four 
{
    public static void main(String[] args) 
    {
        Human allen = new Human();
        allen.breath();
        System.out.println(allen.height);
    }
}

运行结果为:

hu.....hu.....
0

接受外部参数、返回类成员的例子:

package a.b;

class Human
{
    void breath()
    {
        System.out.println("hu.....hu.....");
    }
    
    void AddHeight(int num)
    {
        height = height +num;
        for (int i = 0; i < num; i++)
        {
            breath();
        }
    }
    
    int GetHight()
    {
        return height;
    }
  
    // 默认给成员变量初始化
    private int height = 10;
}

public class four 
{
    public static void main(String[] args) 
    {
        Human allen = new Human();
        allen.AddHeight(5);
        System.out.println(allen.GetHight());
    }
}

运行结果为:
hu.....hu.....
hu.....hu.....
hu.....hu.....
hu.....hu.....
hu.....hu.....
15