类的创建
package yuque.phil616.oop;public class OOP {public static void main(String[] args) {Human Lee = new Human();}}class Human {String name;int height;String getName(){return this.name;}int getHeight(){return this.height;}}
上述代码中,Human的类创建出一个对象实例为Lee,new关键字的意义在于将对象创建出来并储存在内存中。
类的使用
Human Lee = new Human();Lee.height = 170;System.out.println("Lee's name is " + Lee.getHeight());
上述代码中,第一行生成了具体对象后,使用点.运算符获取到了类中的一个变量、即属性,并赋值为170;
在下面第三行中的加号后,使用了类中的方法。
初始化
类提供了一种在被创建时就赋初始值的方法,即为构造方法,在类的实例化对象被创建时,他的构造方法就被调用,不论程序员是否定义了构造方法,构造方法默认被调用。
构造方法
构造方法是一种特殊方法,他没有返回值,且函数名必须与类名一致。
例如下面的构造方法实例:
class Human{Human(){ //Human类的构造方法}}
该构造方法没有任何内容也没有参数,即调用时不会做任何操作。
class Human {String name;int height;Human(String myName,int myHeight){name = myName;height = myHeight;}}
而在这个类中,我们自行定义了一个有参数的构造方法,即有参构造。
当使用new进行创建时,我们就可以把参数传进去。
Human Lee = new Human("Bruce Lee",180);
传入参数后,Lee这个对象的两个属性就有了初始值,即为创建时传入的两个参数。
this
this是Java中的关键字,用于区分参数名和属性名。例如下面的一个构造方法中,计算机无法分清谁是传入的参数,谁是类自己的属性。
class Human {String name;int height;Human(String name,int height){name = name;height = height;}}
此时程序会报错,需要使用this来确认this后的变量一定是类内的属性而非参数
class Human {String name;int height;Human(String name,int height){this.name = name;this.height = height;}}
