Kevag6
Kevag6

Reputation: 135

Accesing private variable from abstract class with access method as abstract

Let's say I have a class called book that is abstract, has a private variable price, and also has it's getter method as abstract.

    public abstract class Book{

        private double price;

        public abstract double getPrice();

    }

Now let's say I have a used Book class that inherits all of Book's attributes, but also has an age associated with it. Also I want this class to override the getPrice method from it's parent class. This is where I get stuck since the price variable is private, and the parent class has an abstract getter method.

    public class UsedBook extends Book{

        private int age;

        //constructor
        public UsedBook(){
            age = 1;
        }

        @Override
        public double getPrice(){
            //How can I implement this method so as a user I can access the price?
        }

    }

Thank You

Upvotes: 5

Views: 55525

Answers (3)

Den Isahac
Den Isahac

Reputation: 1525

If you do not want the price field variable to be publicly accessible from the Abstract class then, you should change the access modifier from private to protected.

protected access modifier means that the field isn't publicly accessible via instance object. However any subclass that inherits the Abstract class directly or indirectly has the protected fields inherited as a field variable, and the same rules goes apply, it cannot be publicly accessible.

So to wrapped it up, the Book class:

public abstract class Book {
  protected double price;

  public abstract double getPrice();
}

The subclass that inherits the Book class:

public class UsedBook extends Book{

  private int age;

  public UsedBook(){
    this.age = 1;
    this.price = 0; // You should also set the field variable from the abstract "Book" class
  }

  @Override
  public double getPrice(){
    return this.price;
  }
}

Upvotes: 9

Mouad EL Fakir
Mouad EL Fakir

Reputation: 3749

Mark price as protected then you can access to it from sub classes :

public abstract class Book{

    protected double price;

    public abstract double getPrice();

}

public class UsedBook extends Book{

...

    @Override
    public double getPrice(){
        return price;
    }

..

}

Upvotes: 2

nhouser9
nhouser9

Reputation: 6780

If all implementations of Book must implement getPrice(), and the implementation is always to just return the price, it should not be abstract. You should just define the getter within your abstract class:

public abstract class Book{

    private double price;

    public double getPrice() {
        return price;
    }

}//Ends book class

If this doesn't work, and you need to directly access the price variable from inheriting classes, then you should change it to be protected instead of private.

Upvotes: 7

Related Questions