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?