`
hdu0704
  • 浏览: 12796 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JAVA继承与多态

    博客分类:
  • java
 
阅读更多
/**
 * 实例化先后顺序:父类的静态变量、子类的静态变量、父类的非静态变量、父类的构造器、子类的非静态变量、子类的构造器
 * 
 * @author zhang
 * 
 */
public class Father {
	public static void main(String[] args) {
		System.out.println("Son constructor");
		Father f = new Son();
		f.f();// 如果子类重写父类的方法,会调用子类的
		f.g();// 如果子类没有该方法,则调用父类的
		((Son) f).h();// 子类有父类没有时,需要强转成子类的类型才可调用
	}

	private int i = 9;

	protected int j;

	public Father() {
		System.out.println("i=" + i + ",j=" + j);
		j = 39;
	}

	int a = print("if before father constructor");
	int b = print("after father constructor");

	private static int x1 = print("static Father.x1 initialized");

	public static int print(String s) {
		System.out.println(s);
		return 47;
	}

	public void f() {
		System.out.println("Father.f()");
	}

	public void g() {
		System.out.println("Father.g()");
	}
}

class Son extends Father {

	public Son() {
		System.out.println("k=" + k);
		System.out.println("j=" + j);
	}

	public int k = print("Son.k initialized");

	private static int x2 = print("static Son.x2 initialized");

	@Override
	public void f() {
		System.out.println("Son.f()");
	}

	public void h() {
		System.out.println("Son.h()");
	}
}

 控制打印:

static Father.x1 initialized

Son constructor

static Son.x2 initialized

if before father constructor

after father constructor

i=9,j=0

Son.k initialized

k=47

j=39

Son.f()

Father.g()

Son.h()

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics