zoukankan      html  css  js  c++  java
  • 动手动脑-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行出现了编译错误,是类型转换时出错了。

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

  • 相关阅读:
    B1001 害死人不偿命的(3n+1)猜想 (15 分)
    A1050 String Subtraction (20 分)
    A1041 Be Unique (20 分)
    B1047 编程团体赛 (20 分)
    B1043 输出PATest (20 分)
    B1042 字符统计 (20 分)
    B1038 统计同成绩学生 (20 分)
    VB计算符号
    vs2008写代码的时候不能输入中文,sogou和google输入法都没有用
    如何彻底关闭Windows7自动更新
  • 原文地址:https://www.cnblogs.com/sonofdemon/p/9894385.html
Copyright © 2011-2022 走看看