动手动脑-Java的继承与多态

一、

class Grandparent 
{


    public Grandparent()
 	{

        	System.out.println("GrandParent Created.");
	
}


    public Grandparent(String string) 
	{

        	System.out.println("GrandParent Created.String:" + string);
	
 }

}



class Parent extends Grandparent
{


    public Parent()
	 {

        	//super("Hello.Grandparent.");

        	System.out.println("Parent Created");
	
       // super("Hello.Grandparent.");

	  }

}



class Child extends Parent 
{


    public Child()
	 {
	
        System.out.println("Child Created");

	  }

}



public class TestInherits 
{


    public static void main(String args[])
	 {

        	Child c = new Child();
	
  }

}

  

由输出可以知道基类继承父类的构造函数时,首先运行父类的构造函数,使用super函数时,代码必须是第一句。

构造函数的作用是对类的初始化,首先要对父类进行。

二、

public class ExplorationJDKSource {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(new A());
	}

}

class A{}

  

输出的是对象在内存空间地址的哈希值 

三、

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);
	}
}

  

当子类父类拥有同名:

对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

将子类型的对象赋给父类,子类型就代替父类对象,如果子类方法想访问父类中被隐藏的同名字段,可以用super关键字来访问它。

四、

第15,16行出现了编译错误,是类型转换时出错了。

将父类对象赋给子类时,要强制转换成父类类型,而将子类对象赋给父类时并不需要。

原文地址:https://www.cnblogs.com/sonofdemon/p/9894385.html