运行 TestInherits.java 示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,
注意这句调用代码是否是第一句,影响重大!
class Grandparent {
public Grandparent(){
System.out.println("GrandParent Created.");
}
public Grandparent(String string) {
System.out.println("GrandParent Created.String:" + string);
}
}
class Parent2 extends Grandparent{
public Parent2(){
super("Hello.Grandparent.");
System.out.println("Parent Created");
// super("Hello.Grandparent.");
}
}
class Child2 extends Parent2 {
public Child2() {
System.out.println("Child Created");
}
}
public class TestInherits {
public static void main(String args[]) {
Child2 c = new Child2();
}
}
结论:通过 super 调用父类构造方法,super必须是子类构造方法中编写的第一个语句
神奇代码:
package Test1;
public class test1 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new A());
}
}
class A{}
结论:
前面示例中,main方法实际上调用的是: public void println(Object x),这一方法内部调用了String类的valueOf方法。 valueOf方法内部又调用Object.toString方法: public String toString() { return getClass().getName() +"@" + Integer.toHexString(hashCode()); } hashCode方法是本地方法,由JVM设计者实现: public native int hashCode()
加号:
public class Fruit
{
public String toString()
{
return "Fruit toString.";
}
public static void main(String args[])
{
Fruit f=new Fruit();
System.out.println("f="+f);
// System.out.println("f="+f.toString());
}
} 结论:
在“+”运算中,当任何一个对象与一个String对象进行连接时,会隐式地调用String对象的toString()方法,
默认情况下,toString方法返回“类名 @ + hashCode”。即Test1.A@8efb846这种形式,为了返回有意
义的信息,子类可以重写并覆盖toString()方法。
public class ParentChildTest {
public static void main(String[] args) {
Parent parent=new Parent();
parent.printValue();
Child child=new Child();
child.printValue();
parent=child;
parent.printValue();
parent.myValue++;
parent.printValue();
((Child)parent).myValue++;
parent.printValue();
}
}
class Parent{
public int myValue=100;
public void printValue() {
System.out.println("Parent.printValue(),myValue="+myValue);
}
}
class Child extends Parent{
public int myValue=200;
public void printValue() {
System.out.println("Child.printValue(),myValue="+myValue);
}
}
结论
当parent=child;仅仅是将parent中有的方法用child的方法代替,所以parent.myValue++;而输出的是child的printValue(),
而printValue()方法中输出的是child.myValue,所以输出的是child.myValue
如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它
原文:https://www.cnblogs.com/kongfanbing/p/11748857.html