Day08子父类继承属性使用

136 阅读1分钟

父类

//父类
public class father {
	int a = 30;
	int d = 40;

}

子类

//子类
public class son extends father{
	int a = 10;
	int b = 20;
	
	void show() {
		System.out.println("-------------");
		
//		子类调用同名属性优先用自己的,要想用父类的同名属性必须用super
//		this 指子类属性 ,super指父类属性
		System.out.println(a);
		System.out.println(this.a);
		System.out.println(super.a);
	}
}

测试类

//测试类
public class extends_1 {
	public static void main(String[] args) {
		son son = new son();
//		子类可使用父类资源
		System.out.println(son.a);
		System.out.println(son.b);
		System.out.println(son.d);
		
//      父类可使用自己的属性
		father father = new father();
		System.out.println(father.a);
//		System.out.println(father.b);  报错,父类使用不了子类属性
		System.out.println(father.d);
	
		son.show();
	}
	
	

}