虽然去年就自学过Java,也写过Android。但是最近又爆出很多问题,很多细节问题,很多基础问题。这让我再次意识到基础的重要性。
class parent { public parent() { System.out.println("parent"); } } public class Child extends parent { public Child() { System.out.println("Child"); } public static void main(String[] args) { // TODO Auto-generated method stub Child c = new Child(); } }结果:
parent Child子类新建对象的时候都会调用父类的构造方法。而如果使用了super那么就调用super指明的父类构造方法,如果没写super,那么默认调用父类的无参构造方法,如果此时父类没有无参构造方法,则报错。
class parent { public parent() { System.out.println("parent"); } public parent(String name){ System.out.println("I'm "+name); } } public class Child extends parent { public Child() { super("jelly"); System.out.println("Child"); } public static void main(String[] args) { // TODO Auto-generated method stub Child c = new Child(); } }答案是:
I'm jelly Child
class parent { String name; public parent(String name){ this.name=name; } }因为参数名和成员名重复了,所以一般都会用this来引用name成员。
class Parent { public void callMe() { System.out.println("Call me father!"); } } public class Child extends Parent { static String name; public void callMe() { System.out.println("Call me child~"); } public static void main(String[] args) { // TODO Auto-generated method stub Parent p = new Child(); p.callMe(); } }结果是:
Call me child~这就是动态绑定。
class Parent { public void callMe() { System.out.println("Call me father!"); } } interface Game { public void gamename(); } public class Child extends Parent implements Teacher { static String name; public void callMe() { System.out.println("Call me child~"); } @Override public void gamename() { // TODO Auto-generated method stub System.out.println("I love LOL"); } public static void main(String[] args) { // TODO Auto-generated method stub Parent p = new Child(); p.gamename();//注意这句 } }
Parent obj[]=new Parent[5]; for (int i = 0; i < 5; i++) { ((Game)obj[i]).gamename(); }
原文地址:http://blog.csdn.net/guodongxiaren/article/details/40742929