java面向对象基础:this关键字和构造方法
this关键字
this表示当前对象
作用:
获取当前对象的属性.
使用this调用构造方法.
构造方法
在做对象实例化的时候,如何一开始就给属性赋值?
用构造方法可以实现!
对象实例化的时候一定会调用构造方法.
如果没有构造方法,实例化对象时会调用一个默认无参的构造方法.
package cn.xtnotes.pojo;
public class Dog2 {
//定义类的属性
String nick;
String color;
int age;
//定义构造方法
public Dog2(String nick1,String color,int age) {
this.nick=nick1;
this.color=color;
this.age=age;
}
public static void main(String[] args) {
Dog2 dog=new Dog2("小白","白色",8);
System.out.println(dog.nick);
System.out.println(dog.color);
System.out.println(dog.age);
}
}
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/198.html
文章版权归作者所有,未经允许请勿转载。
THE END