Ankur
Ankur

Reputation: 51100

Why aren't inherited properties available in subclasses

I am trying to use a member variable called value in a subclass.

My super class is called SType and my subclass is called SResource.

I have a variable in the super class SType called value

I want this to be inherited by the subclass, how do I do this. The class looks like this

public class SType {

    private String value;

    public String getValue(){
        return this.value;
    }
    public void setValue(String value){
        this.value = value;
    }
}

NOTE: I edited the question to make it more clear (given the comment below). Thanks it was a simple solution, just had to make the variable protected rather than `private

Upvotes: 1

Views: 127

Answers (3)

Siten
Siten

Reputation: 4533

instead of private try:

protected String value;

b.cos private can only access current class only. while projected can access sub class

your question is appropriate but the meaning of private in the java meance to protect current variable or method from outside of the class.

Upvotes: 1

duffymo
duffymo

Reputation: 308763

You can - make it protected instead of private.

Upvotes: 2

Petar Ivanov
Petar Ivanov

Reputation: 93030

In order to access a superclass variable in a subclass, it has to be declared public or protected in the super class. Maybe yours is private?

When you had private String value in the child class - this is a completely new variable - it's not the one from the parent class i.e. you have two distinct private variables (I am assuming the superclass one is private).

Upvotes: 4

Related Questions