MrSebo
MrSebo

Reputation: 49

Initialize private variables from subclass

I have an upcoming exam and one of practice tasks is the following:

My problem with this task is the two private variables name and course. Private means they cannot be overwritten by the subclasses, right? How am I supposed to initialize those variables from the subclasses?

This is my code so far, but it does not work:

class Bachelor extends Student{
    Bachelor (String n, String c){
        name = n;
        course = c;
    }
    void printlabel() {
        System.out.println("%s\nBachelor %s",name, course);
    }
}
class Master extends Student{
    Master (String n, String c){
        name = n;
        course = c;
    }
    void printlabel() {
        System.out.println("%s\nMaster %s",name, course);
    }
}

public abstract class Student {
    private String name;
    private String course;
    public Student (String n, String c) {
        name = n;
        course = c;
    }
    void printname() {
        System.out.println(name);
    }
    void printcourse() {
        System.out.println(course);
    }

    public static void main(String[] args) {
        Bachelor rolf = new Bachelor("Rolf", "Informatics");
        rolf.printname();

    }
    abstract void printlabel();
}

Detailed description: Create class Student with two private objectvariables name and course. Then create a constructor that initializes those variables, the methods printname() and printcourse() and the astract method printlabel().

Then create two subclasses Bachelor and Master. They are supposed to have a constructor and overwrite the abstract method.

e.g.

Bachelor b = new Bachelor("James Bond", "Informatics");
b.printlabel();

Is supposed to return the name, the classname and the course.

Upvotes: 1

Views: 595

Answers (2)

IdiakosE Sunday
IdiakosE Sunday

Reputation: 116

Add a pubic method that sets the private properties. Call said public methods from contructor.

Upvotes: 0

assylias
assylias

Reputation: 328598

You can access the superclass constructor with a call to super(). So in your subclass, just call super(n, c); instead of assigning the variables directly and you should get the expected behaviour.

Upvotes: 1

Related Questions