简体   繁体   English

在Java中使用没有实例变量的实例方法

[英]Using a instance method without an instance variable in Java

I'm new to the syntax of Java and was looking at a question in regards to the protected access modifier. 我是Java语法的新手,正在研究有关受保护的访问修饰符的问题。 Titled "Protected member access from different packages in java - a curiosity". 标题为“从Java中的不同包中保护成员访问-出于好奇”。

Protected member access from different packages in java - a curiosity 受保护的成员从Java中的不同包进行访问-好奇

In that question the following code was referred to: 在该问题中,引用了以下代码:

package packageOne;

public class Base{
    protected void display(){
    system.out.println("in Base");
    }
}

package packageTwo;

public class Derived extends packageOne.Base{
    public void show(){
    new Base().display();//this is not working throws compilation error that
                         //display() from the type Base is not visible   
    new Derived().display();//is working
    display();//is working
    }
}

My question is in regard to the last line of code. 我的问题是关于代码的最后一行。

display(); //is working

For me, this line does not compile and that makes sense, because the method is refereed to from a static context. 对我来说,这行代码无法编译,因此很有意义,因为该方法是从静态上下文中引用的。

I comprehend the rules around using protected members and reference variables types, but using a non static protected member without a reference variable seems to confuse me. 我了解使用受保护成员和引用变量类型的规则,但是使用没有引用变量的非静态受保护成员似乎使我感到困惑。

Reading the answers, I do not see anyone else having a problem with this, except for the last answer. 阅读答案,除了最后一个答案,我看不到其他人对此有任何疑问。 But that answer does't seem to relate to the question asked. 但是那个答案似乎与所提出的问题无关。

Sorry this question might seem pedantic or primitive, but it is bugging me as this breaks OO programming. 抱歉,这个问题似乎很古怪或原始,但是它困扰着我,因为这破坏了OO编程。

Am I missing something here? 我在这里想念什么吗? please advice, 请指教,

Thanks 谢谢

For me, this line does not compile and that makes sense, because the method is refereed to from a static context. 对我来说,这行代码无法编译,因此很有意义,因为该方法是从静态上下文中引用的。

No, it isn't. 不,不是。 It's inside an instance method ( show ). 它在实例方法( show )内。 In Java, within instance methods, the this. 在Java中,实例方法中的this. is optional when referring to other instance methods and fields. 在引用其他实例方法和字段时是可选的。 Eg, if the call to display is in an instance method (and it is in that code), display(); 例如,如果对display的调用在实例方法中(并且在该代码中),则display(); and this.display(); this.display(); are exactly the same thing. 是完全一样的东西。

The method is not referred to from a static content. 该方法不是从静态内容中引用的。
show() is an instance method. show()是一个实例方法。
Are you trying the same code, but within a main() ? 您是否在main()中尝试相同的代码?

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

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