简体   繁体   English

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

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

Here is my question, super keyword is used only in case of inheritence ? 这是我的问题,仅在继承的情况下使用super关键字吗? In terms of inheritence, what is the difference between this and super ? 在继承方面, thissuper什么区别?

  • this refers to the current object , ie it's a reference this是指当前对象 ,即它是一个引用
  • super refers to the super class , ie it's a scoping mechanism super是指超类 ,即它是一种作用域机制

The current object is the same object as the object of the superclass. 当前对象与超类的对象相同 If you have a Dog that extends Animal , and do new Dog() then you create 1 object, and this object is both the Animal instance and the Dog instance. 如果您有一个扩展AnimalDog并执行new Dog()那么您将创建1个对象,并且该对象既是Animal实例又是Dog实例。

Here's an example 这是一个例子

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
    }
}

this refers to current object, while super refers to current object's parent class. 这是指当前对象,而super是指当前对象的父类。

Consider this: 考虑一下:

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.

相关问题 java中这个和超级关键字有什么区别? - What's the difference between this and super keywords in java? 之间有什么区别<? super E>和<? extends E> ? - What is a difference between <? super E> and <? extends E>? “”和“”之间有什么区别,我如何用char来测试前者? - What is the difference between “” and “ ”, and how do I test the former in terms of a char? 在阴影方面,Java中的每个循环和传统for循环之间有什么区别? - What is the difference between for each and traditional for loop in Java in terms of shadowing? try-catch和throws Exception在性能方面有什么区别? - What is the difference between try-catch and throws Exception in terms of performance? 用最简单的术语来说,同步到存储库和更新到 HEAD 之间有什么区别? - In the simplest terms, what is the difference between synchronize to repository and update to HEAD? Java RESTful服务 - QueryParam和PathParam在使用方面有什么区别? - Java RESTful services - What is the difference between QueryParam and PathParam in terms of their usage? 在图像处理方面,空间特征和时间特征有什么区别? - what's the difference between spatial and temporal characterization in terms of image processing? Java(UML)中的术语调用,委托和分派之间有什么区别 - What is the difference between terms invoke, delegate and dispatch in Java (UML) class.super.method和class.method有什么区别? - What is the difference between class.super.method and class.method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM