【Java 基础篇】【第四课】初识类

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

 

我发现的类和C++不同的地方:ide

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

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

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

 

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

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);
    }
}

运行结果为:ci

hu.....hu.....
0it

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

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.....
15class

相关文章
相关标签/搜索