简体   繁体   English

Java使用覆盖方法

[英]Java using overriden methods

I am a noob and I need some help. 我是一个菜鸟,我需要一些帮助。

So I have this abstract class with a private variable. 所以我有一个带有私有变量的抽象类。 I also have a method named getThing() to return that. 我还有一个名为getThing()的方法来返回它。

I have a class that extends that abstract class, and it too has a private variable and a method that overrides the original to get the value from the abstract class. 我有一个扩展该抽象类的类,它也有一个私有变量和一个覆盖原始类的方法来从抽象类中获取值。

Well the only way to be able to access both values is by creating a second method in the subclass called getSuperThing, and using the super in that. 那么能够访问这两个值的唯一方法是在子类中创建一个名为getSuperThing的第二个方法,并在其中使用super。 Well I was just wondering out of curiosity if there was some easier way to do that and be able to access the abstract classes method by doing something like objectNae.super.getThing(). 好吧,我只是出于好奇而想知道是否有更简单的方法可以通过执行类似objectNae.super.getThing()的方式来访问抽象类方法。

Thanks ;) 谢谢 ;)

The variable is private and so can only be referenced by the containing (abstract) class. 变量是private ,因此只能由包含(抽象)类引用。 As you have stated, from a subclass, you can invoke the superclass method (rather than the overridden one). 如您所述,从子类中,您可以调用超类方法(而不是重写方法)。

If you want to make the variable accessible from the subclass directly (without requiring the accessor method), make it protected instead. 如果你想直接从子类中的变量访问(无需访问方法),使其protected代替。 Here is the documentation on Controlling Access to Members of a Class . 以下是有关控制对类成员的访问的文档。

If I understand your question correctly, then you just shouldn't override the abstract class' method in the concrete subclass. 如果我正确理解你的问题,那么你就不应该在具体的子类中覆盖抽象类的方法。 No need to, unless you need the subclass to return a different value than that returned by the abstract class (and that would suggest poor design). 除非你需要子类返回与抽象类返回的值不同的值(这表明设计不佳),否则不需要。

Rather, the abstract class' method will be accessible as a method of the subclass. 相反,抽象类'方法可以作为子类的方法访问。

So, if you have: 所以,如果你有:

public abstract class AbstractClass {
  private int value = 3;

  public int getValue() {
   return value;
  }
}

public class ConcreteClass extends AbstractClass {
}

then you should be able to do: 那么你应该能够做到:

new ConcreteClass().getValue()

I don't think you have other ways than calling super.getThing() in the subclass's getThing() or getSuperThing() method. 我不认为除了在子类的getThing()或getSuperThing()方法中调用super.getThing()之外,还有其他方法。 Abstract class must be subclassed before being used. 抽象类在使用之前必须是子类。

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

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