简体   繁体   中英

Java: Adding Fields to Sub-Class Constructors?

For example, say I have the 3 classes Person, Student and Teacher. The Person class would have general details about the people (name, age, email etc) which both the Student and Teacher class will extend. On top of this though, these classes will also have their own unique fields (eg wage & courseTaught (or "tought"?) for Teacher and schoolYear & classNumber for Student). If I just show the initial code I've got, maybe someone could point me in the right direction. Because Person doesn't have a courseTaught field, currently I'm just getting the output "Josh (null)" rather than "Josh (Computer Science)". Any help would be appreciated :)

public class Main {
    public static void main(String args[]){
        Teacher t = new Teacher("Josh", "Computer Science");
        System.out.println(t.name + " (" + t.courseTaught + ")");
    }
}

public class Person {

    String name;

    public Person(String pName){
        name = pName;
    }
}

public class Teacher extends Person{

    String courseTaught;

    public Teacher(String tName, String tCourseTaught){
        super(tName);
    }
}

The problem is simpler than you think. You're on the right track but you forgot to assign courseTaught in your Teacher constructor. The initial value of courseTaught is null and it stays that way because you never assign it to anything.

You'd want something like this:

public Teacher(String tName, String tCourseTaught){
    super(tName);  // <- takes care of Persons's field
    courseTaught = tCourseTaught; // <- but don't forget to set the new field, too.
}

And yes, "taught" is the correct word.

As an aside, since you did tag your question "oop", you may want to check out this article on encapsulation for some information about the use of "getters" and "setters".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM