2

Suppose an abstract super class contains a private variable called price of type double.

Now suppose the variable has been declared but not initialized. The super class contains accessor methods, however the setter method is abstract, thus it must be overridden in a sub-class, but, as the super variable is private, is there any way to initialize this variable from a sub-class?

Consider the following example: I have 4 Classes; Book(abstract super), NonFiction(sub), Fiction(sub), Tester(class to test what happens).

The Book Class:

public abstract class Book {

private String title;
private double price;

Book(String name){
    title = name;
}

public String getTitle(){
    return title;
}

public double getPrice(){
    return price;
}

public abstract void setPrice(double cost);
}

The Fiction Class

public class Fiction extends Book{

Fiction(){
    super("Harry-Potter");
    setPrice(24.99);
}

@Override
public void setPrice(double cost) {
}
}

The NonFiction Class

public class NonFiction extends Book {

NonFiction(){
    super("Head-first Java");
    setPrice(37.99);
}

public void setPrice(double cost) { 
}
}

The Tester Class

public class Challenge {
public static void main(String[] args){


Fiction fictionBook = new Fiction();
NonFiction NonFictionBook = new NonFiction();

Book[] theList = new Book[2];
theList[1] = NonFictionBook;
theList[0] = fictionBook;

System.out.println("Title of fiction book: \n"+theList[0].getTitle());
System.out.println("Title of non fiction book \n"+theList[1].getTitle());   
System.out.println("Title - "+theList[0].getTitle()+" -" + theList[0].getPrice());
System.out.println("Title - "+theList[1].getTitle()+" -" + theList[1].getPrice());
}

}

The expected output should be:

Title of fiction book: Harry Potter Title of non fiction book: Head-First Java Title-Harry Potter Cost-$24.99 Title-Head-First Java Cost-$37.99

Is there a way to access the private variable without changing the scope to protected?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
RamanSB
  • 1,162
  • 9
  • 26

1 Answers1

2

The point of making a variable private is to prevent anything outside the class from accessing or changing it. If the developer of the class wanted it to be viewable or changeable by subclasses it would have been made protected. However, it is possible to change the value using reflection (as long as the security manager is not configured to disallow that). See How do I read a private field in Java?

(Btw, just to nitpick, if you don't initialize an instance variable it gets a default value set for it, price will be set to 0.0D if you don't assign it an initial value. Leaving an instance or class variable uninitialized isn't really an option.)

Community
  • 1
  • 1
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276