简体   繁体   English

java中这个和超级关键字有什么区别?

[英]What's the difference between this and super keywords in java?

Check my coolMethod, babes: 检查我的coolMethod,辣妹:

package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod. My Moo Class,扩展了我的Zoo类,充满了做同样事情的方法,这就是调用我的coolMethod。

package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

And my main, that calls my Moo class functionalities. 而我的主要内容是调用我的Moo类功能。

package javacert1;

import zoo.Moo;

public class Main {


    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}

As you can see, all those four calls get the same results. 如您所见,所有这四个调用都得到相同的结果。 I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. 我正在学习Java,我练习了一个使用“this”的例子,但我曾在其他地方看到过使用“super”,所以我测试了它,结果也是如此。 Why is this? 为什么是这样? What's the major difference between a this and super keyword? this和super关键字之间的主要区别是什么?

Since you have only one coolMethod , it is called in each case, regardless of qualifiers. 由于您只有一个coolMethod ,因此无论使用何种限定符,都会在每种情况下调用它。 However, if you override your method in Moo eg like this 但是,如果你在Moo覆盖你的方法,就像这样

public class Moo extends Zoo {
    public String coolMethod() {
        return "Yeah dude!";
    }
    // the rest is the same as above...
}

you will notice the difference between the calls to coolMethod() and this.coolMethod() versus the call to super.coolMethod() . 你会注意到对coolMethod()this.coolMethod()的调用与对this.coolMethod()的调用之间的super.coolMethod()

this can be pointing to current object this可以指向当前对象

super can be used for accessing Super class metods & variables super可用于访问Super class metods和变量

this() can be used to invoke a constructor of the same class this()可用于调用同一个类的构造函数

super() can be used to invoke a super class constructor super()可用于调用超类构造函数

Difference with examples 与例子不同

You are not overriding the coolMethod and you are inheriting it. 你没有覆盖coolMethod并继承它。
As a result it calls the same method. 结果它调用相同的方法。
Override coolMethod and see what happens. 覆盖coolMethod ,看看会发生什么。
super will call the method of base. super会调用base的方法。
this will call method in this object this将调用此对象中的方法

"this" refers to the object you're in. "super" refers to the parent of this object. “this”指的是你所在的对象。“super”指的是这个对象的父级。 I think you're missing the difference because of some other things you have going on. 我认为你因为你正在进行的其他一些事情而错过了这种差异。

For example, this code 例如,这段代码


public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}



public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

The method "coolMethod" is defined in Zoo, but it's a public method so it is naturally inherited by Moo. 方法“coolMethod”在Zoo中定义,但它是一个公共方法,因此它自然地被Moo继承。 So, when you're within your Moo class and you call this.coolMethod or super.coolMethod, you end up with exactly the same thing. 所以,当你在你的Moo课程中并且你调用this.coolMethod或super.coolMethod时,你最终会得到完全相同的东西。 Where things get far more interesting is if you override the coolMethod in your subclass, like this: 事情变得更有趣的是,如果你覆盖子类中的coolMethod,就像这样:


public class Zoo {
    public String coolMethod() {
        return "Wow baby!";
    }
}

public class Moo extends Zoo {

    @Override
    public String coolMethod() {
        return "Moo baby!";
    }

    public void doIt() {
        System.out.println("Using super: " + super.coolMethod());
        System.out.println("Using this: " + this.coolMethod());
    }
}

Try executing "doIt" in that case and I think you'll see the difference much easier. 在这种情况下尝试执行“doIt”,我认为你会更容易看到差异。

Cool example, overmann :) 很酷的例子,overmann :)

Here is another example ... has 2 source files - LevelSub.java which extends LevelSup.java 这是另一个例子......有2个源文件 - LevelSub.java,它扩展了LevelSup.java

Save the 2 in some folder, compile using "javac LevelSub.java" (compiler will know from "extends" that it has to compile "LevelSup.java", too), and run "java LevelSub". 将2保存在某个文件夹中,使用“javac LevelSub.java”编译(编译器将从“extends”知道它还必须编译“LevelSup.java”),并运行“java LevelSub”。 The comments in the source code should tell you the difference. 源代码中的注释应该告诉您区别。

this and super are used when there is a name clash for variables or methods (eg, same name is used in super/sub classes or in a method body, or you want to call a method from the superclass that has been overridden). 当变量或方法存在名称冲突时使用this和super(例如,在超类/子类或方法体中使用相同的名称,或者您想从已被覆盖的超类中调用方法)。 "this" refers to the current object instance and "super" refers to the one it is inheriting from. “this”指的是当前的对象实例,“super”指的是它继承的实例。 For no name clashes, the this or super prefix are redundant. 对于没有名称冲突,这个或超级前缀是多余的。

public class LevelSub extends LevelSup {
    protected String myName;

    public LevelSub (String myName) {
        super ("SuperClass");
        this.myName = myName;       // sets up instance variable
    }

    public void print () {
        System.out.println ("Hi, this is " + myName); // refers to this.myName
        System.out.println ("I am inherited from " + super.myName);
        System.out.println ("also known as " + defaultName); // gets from superclass
        super.print();           // overridden method of superclass
    }

    public static void main (String[] args) {
        new LevelSub("SubClass").print();
}}

and the other source ... 和另一个来源......

public class LevelSup {
    // cannot be private if accessed by subclass
    protected String myName, defaultName = "TopLevel";

    public LevelSup (String name) {
        myName = name;      // this not required, no name clash
    }

    // cannot be private if accessed by subclass
    public void print () {
        System.out.println ("Hi, this is " + myName);
    }
}

In this case, they will do nothing different. 在这种情况下,他们不会做任何不同的事情。

However, if you were to override coolMethod in the Moo class, the call to the super version will call the version in the Zoo class, but all the other versions will call the new overridden one. 但是,如果您要在Moo类中覆盖coolMethod ,则对super版本的调用将调用Zoo类中的版本,但所有其他版本将调用新的重写版本。

To see the difference, overwrite the coolMethod in your subclass Moo: 要查看差异,请覆盖子类Moo中的coolMethod:

public String coolMethod() {
    return "Moo baby!";
}

我建议你在Moo类中创建一个coolMethod,它打印出与Zoo类中不同的东西

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

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