动手动脑

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

posted @ 2018-11-07 22:42  故事-已开始。  阅读(226)  评论(1)    收藏  举报