• 动手动脑


    1.

    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();
        }
    
    }
    运行结果:

    ,在parent中,注释部分必须父类在前,否则出错!

    2.

      package Test;
      public class ExplorationJDKSource {
      
          /**
           * @param args
           */
          public static void main(String[] args) {
              System.out.println(new A());
          }
     
     }
     
     class A{}
    运行结果;

    3.
    1 public class ParentChildTest {
     2     public static void main(String[] args) {
     3         Parent parent=new Parent();
     4         parent.printValue();//1
     5         Child child=new Child();
     6         child.printValue();//2
     7         
     8         parent=child;//将子类赋值给父类value变为200
     9         parent.printValue();//3,输出200
    10         
    11         parent.myValue++;//父类的value+1,对子类的value之不改变
    12         parent.printValue();//4
    13         
    14         ((Child)parent).myValue++;//先进行强制转化变为子类类型,值不会变化,在加一201
    15         parent.printValue();
    16         
    17     }
    18 }
    19 
    20 class Parent{
    21     public int myValue=100;//101
    22     public void printValue() {
    23         System.out.println("Parent.printValue(),myValue="+myValue);
    24     }
    25 }
    26 class Child extends Parent{
    27     public int myValue=200;//201
    28     public void printValue() {
    29         System.out.println("Child.printValue(),myValue="+myValue);
    30     }
    31 }
    运行结果:

    因为子类继承了父类,所以子类可以赋值给父类,但是父类不可以赋值给子类,使用关键字super,可以调用父类的对象

  • 相关阅读:
    面试题 33 把数组排成最小的数
    面试题32 1的数目
    面试题29 数组中出现次数超过一半的数字
    LeetCode_Combination Sum II
    LeetCode_Combination Sum
    面试题27 二叉搜索树转换为双向链表
    面试题26 复杂链表的复制
    面试题24 二叉搜索树的后序遍历序列
    LeetCode_Binary Tree Inorder Traversal
    省选模拟57 题解
  • 原文地址:https://www.cnblogs.com/yishaui/p/9926298.html
Copyright © 2020-2023  润新知