繁体   English   中英

在继承方面,super和this有什么区别?

[英]What is the difference between super and this in terms of inheritence?

这是我的问题,仅在继承的情况下使用super关键字吗? 在继承方面, thissuper什么区别?

  • this是指当前对象 ,即它是一个引用
  • super是指超类 ,即它是一种作用域机制

当前对象与超类的对象相同 如果您有一个扩展AnimalDog并执行new Dog()那么您将创建1个对象,并且该对象既是Animal实例又是Dog实例。

这是一个例子

class Dog extends Animal {

    public void treatWell(DogSpa spa) {
        spa.takeCareOf(this);      // pass this object to the spa
    }

    public void makeSound() {
        System.out.println("bark");
        super.makeSound();         // call makeSound in Animal scope
    }
}

这是指当前对象,而super是指当前对象的父类。

考虑一下:

class Parent {
    protected int value;
    public void test() {
         //print parent
    }
}

class Child extends Parent {
    public void test() {
       //print child
    }
    private void someMethod() {
        this.test();//will print child
        super.test();//will print parent
    }        
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM