简体   繁体   中英

Accessing a variable in a subclass through a superclass method (Java)

I am building two classes: Person and namedPerson . Person is the superclass of namedPerson . I need the method printPerson to print out the first and last name of a namedPerson , but Person can only receive the last name, and namedPerson receives both first and last names. My code is as follows:

public abstract class Person {

   String Lastname;
   String Name;

   public Person(String Lastname){
     this.Lastname = Lastname;
   }

   public void printPerson() {
     System.out.println("Name: " + Name);
     System.out.println("Last name: " + Lastname);
   }

Here is namedPerson :

public class namedPerson extends Person {

   String Lastname;
   String Name;

   public namedPerson(String Lastname){
     super(Lastname);
     this.Name = "Bob";
   }

When I do the following:

namedPerson Bob = new namedPerson("Smith");
Bob.printPerson();

I get:

Name: null
Last name: Smith

When I need to get:

Name: Bob
Last name: Smith

Thanks for the help!

This is because you are redeclaring the instance variables Lastname and Name inside the sub-class which makes no sense because you already inherited them from the superclass.

All you have to do is to remove them from the sub-class:

public class namedPerson extends Person {

   public namedPerson(String Lastname){
     super(Lastname);
     this.Name = "Bob";
   }
}

Try this:

    public abstract class Person {

    String Lastname;
    

    public Person(String Lastname) {
        this.Lastname = Lastname;
    }

    public void printPerson() {
        System.out.println("Last name: " + Lastname);
    }

    public static void main(String[] args) {
        NamedPerson namedPerson = new NamedPerson("firstName", "Name");
        namedPerson.printPerson();
    }
}

class NamedPerson extends Person {

    String name;

    public NamedPerson(String Lastname, String name) {
        super(Lastname);
        this.name = name;
    }

    @Override
    public void printPerson() {
        super.printPerson();
        System.out.println("Name: " + name);
    }
}

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