zoukankan      html  css  js  c++  java
  • 动手动脑

    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,可以调用父类的对象

  • 相关阅读:
    Ext4文件系统架构分析(二)
    Ext4文件系统架构分析(一)
    STL容器与拷贝构造函数
    左值、右值与右值引用
    C++ 11右值引用
    读书笔记_Effective_C++_条款二十五: 考虑写出一个不抛出异常的swap函数
    《Effective C++》item25:考虑写出一个不抛异常的swap函数
    CC++ vector 构造函数 & 析构函数
    复制构造函数 与 赋值函数 的区别
    a++与++a
  • 原文地址:https://www.cnblogs.com/yishaui/p/9926298.html
Copyright © 2011-2022 走看看