JohnMcClane
JohnMcClane

Reputation: 128

Making parent class private but make fields useable with 'extend' in subclass

I am having some troubles with my Java code. I need the fields and the parent class to be private YET they have to be useable in the subclass.

I need to run JUnite tests on the class and field modifier. Error code when running: Error PS: I tried making them protected but then you can change the fields.

Could use some advice. Thanks in advance

Parent class:

package logica;
import java.util.Objects;

public class Uitgave {
private String titel;
private double prijs;

private Uitgave(String titel, double prijs){
    this.titel = titel;
    this.prijs = prijs;
}

Subclass:

package logica;

import java.util.Objects;

public class Boek extends Uitgave{
private String auteur;
private int paginas;
public Boek(String titel,String auteur, double prijs, int paginas){
    super(titel,prijs);
    if(titel==null || auteur==null || prijs<0 || paginas<0){
        throw new IllegalArgumentException
("Controleer uw gegevens op fouten. 
Prijs en aantal paginas kan niet negatief zijn, 
het boek moet een titel en auteur hebben");
    }

    this.auteur = auteur;
    this.paginas = paginas;
}

Upvotes: 0

Views: 66

Answers (1)

Madura Pradeep
Madura Pradeep

Reputation: 2454

You have 2 options.

  1. Change private access modifier in to at least protected. But if you do this, the variable can access inside the package. Not only sub class (In Java, difference between default, public, protected, and private).

  2. Define get method in parent class for private variable and use super.getX() in sub class.

Upvotes: 1

Related Questions