Java inheritance 继承

package com.dingfei.j2ee.inheritance;

/**
 * 成员变量:实例变量与静态变量与引用变量声明的类型进行绑定,属于静态绑定,编译时就做了绑定
 * 实例方法:实例方法与引用变量实际引用的对象的方法进行绑定,属于动态绑定,由JVM运行时动态绑定
 * 静态方法:静态方法与引用变量声明的类型进行绑定,属于静态绑定,编译时就做了绑定
 * 
 * @author Jeffy Ding
 *
 */
public class ExtendsTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Base b = new Base();
		Base bs = new Sub();
		Sub s = new Sub();
		
		/**
		 * Base的method方法没有被子类覆盖,子类重载的Base的method方法
		 * Base的amethod方法被子类覆盖,所以运行时显现为多态
		 * 成员变量与声明类型进行静态绑定
		 */
		b.method(bs);
		b.method(b);
		b.method(s);
		b.amethod();  //静态方法静态绑定
		
		bs.method(b);
		bs.method(bs);
		bs.method(s);
		bs.amethod();
		
		s.method(b);
		s.method(bs);
		s.method(s);
		s.amethod();  //静态方法静态绑定
		
		/**
		 * b and bs are both declared as Base, so both are static binding
		 * 打印父类的成员变量值
		 */
		System.out.println("Base.a: " + b.a);
		System.out.println("Base.a: " + b.b);
		System.out.println("Base.a: " + b.c);
		System.out.println("Base.a: " + b.name);  
		
		System.out.println("Declared as Base.a: " + bs.a);
		System.out.println("Declared as Base.a: " + bs.b);
		System.out.println("Declared as Base.a: " + bs.c);
		System.out.println("Declared as Base.a: " + bs.name);
		
		/**
		 * s is declared as Sub, so is static binding
		 * 打印子类的成员变量值
		 */
		System.out.println(s.a);
		System.out.println(s.b);
		System.out.println(s.c); 
	}
}

class Base{
	public String a = "Hello";
	protected int b = 13;
	double c = 5;
	private int d = 8;
	
	static String name = "Base name"; 
	
	public void method(Base b){
		System.out.println("Base Class");
	}
	
	public void amethod(){
		System.out.println("Base amethod()");
	}
}

class Sub extends Base{
	public String a = "Hello-sub";
	protected int b = 131;
	double c = 51;
	
	static String name = "Sub name"; 
	
	/**
	 * 这个事重载不是覆盖
	 * 重载:相同的方法名不同的参数签名,返回类型可以不一样,修饰符可以不一样
	 * 覆盖:与父类具有相同的方法名、参数签名、返回类型
	 * @param s
	 */
	public void method(Sub s){
		System.out.println("Sub Class");
	}
	
	/**
	 * 这个才是覆盖
	 * @param s
	 */
	/*public void method(Base b){
		System.out.println("Sub Class");
	}*/
	
	/**
	 * overriding覆盖父类的amethod()
	 */
	public void amethod(){
		System.out.println("Sub amethod()");
	}
}
 

你可能感兴趣的:(java,jvm,C++,c,C#)