首页 > 其他 > 详细

动手动脑

时间:2018-11-07 22:42:27      阅读:188      评论:0      收藏:0      [点我收藏+]

技术分享图片

package 作业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();
    运行结果:技术分享图片

运行子类的构造函数会先执行父类的构造函数。若将//super("Hello.Grandparent.");前//去掉之后运行就结果就会变成:

技术分享图片

 

有了super()语句会执行其调用的构造函数,若将其放在第二行,则会报错

技术分享图片

(构造函数调用必须是构造函数中的第一个语句)这是显示的错误。

总结:通过 super 调用父类构造方法,必须是子类构造方法中的第一个语句。若父类中同时存在有参构造函数和无参构造函数,若子类构造函数什么也没写则默认调用无参构造函数,若加上super(),则根据super()来确定,若父类只有有参构造函数,则必须在写子类构造函数时加上super();

 

 

 

请自行编写代码测试以下特性(动手动脑): 在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

package 作业1;

 class TEXT {
    public void print() {
        System.out.println("我是爸爸");        
    }

}
class Son extends TEXT{
    public void print() {
     System.out.println("我是儿子");
    }
    
     public void Fuprint(){
         super.print();
    }
}
public class DSDN {
public static void main(String[] args) {
Son s=new Son();
s.Fuprint();
}
}

运行结果:技术分享图片

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=1;
    public void printValue() {
        System.out.println("Parent.printValue(),myValue="+myValue);
    }
}
class Child extends Parent{
    public int myValue=2;
    public void printValue() {
        System.out.println("Child.printValue(),myValue="+myValue);
    }

运行结果:
技术分享图片

先定义了一个父类对象以及子类变量,输出就显示出来第一二句,然后用children对象给parent对象赋值,parent对象的myValue变为2;parent函数printvalue也被覆盖,于是就有了第三句,value++是先输出再加一,于是输出第四句,然后强转输出,这是value已经是3,先输出在加一有了第五句。

 

动手动脑

原文:https://www.cnblogs.com/2205254761qq/p/9926188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!