user1386048
user1386048

Reputation:

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.

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. 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().

Thanks ;)

Upvotes: 1

Views: 95

Answers (3)

lijie98
lijie98

Reputation: 617

I don't think you have other ways than calling super.getThing() in the subclass's getThing() or getSuperThing() method. Abstract class must be subclassed before being used.

Upvotes: 0

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

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()

Upvotes: 1

Greg Kopff
Greg Kopff

Reputation: 16625

The variable is private and so can only be referenced by the containing (abstract) class. 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. Here is the documentation on Controlling Access to Members of a Class.

Upvotes: 3

Related Questions