this如何调用属性/方法/构造器及原则?以及与super的对比?

package pro14;
/*this.属性  :当前对象
 * 
 *this.普通方法:直接就是this.方法名
 *
 *this调用构造器的原则:
 *1.在调用的方式上:需要使用this来调用构造器,而不是通过构造器的名字来调用
 *2.在调用的位置上: 只能在构造器里对构造器进行调用
 *3.在语句的顺序上:只能放在构造器的第一条语句上
 *
 * */
public class Person {
	
	String name;
	int age;
	
	public Person(){
		
		System.out.println("新对象实例化1");
	}
	
	public Person(String name){
		this();
		System.out.println("新对象实例化2");
		this.name=name;
	}
	
	public Person(String name,int age){
		 //有参的构造方法
		this(name);
		System.out.println("新对象实例化3");
	
		this.age=age;
	    
		this.show(); 
	}
	
	public String getInfo(){
		return "姓名"+name+"年龄"+age;
	}
	
	public void show(){
		System.out.println("今天的天气不太好");
	}
	
	public static void main(String[] args) {
		Person pe=new Person("张三",33);
		System.out.println(pe.getInfo());
		
	}
	
}

package pro14;
/*
 * 在实例化子类对象的时候会通过子类的无参的构造器去调用父类的无参的构造器
 * 
 * super();
 * 1.必须写在子类的构造器的第一行
 * 2.super() super(name)
 * */
public class Teacher extends Person1{
	
	public Teacher(){
		super();
		System.out.println("子类的构造器");
	}
	
	public Teacher(String name){
		super(name);
		System.out.println("有参的构造器");
		super.show();
	}

猜你喜欢

转载自blog.csdn.net/Java_stud/article/details/82317397
今日推荐