Search code examples
javaclassinheritancesubclasssuperclass

Having trouble regarding inheritence & utilising attributes in different classes


I am new to Stack Overflow & Java, and I am having trouble figuring out a way to make a class that utilizes attributes from two other classes. It doesn't need all the attributes just select ones.

I have a house, town and a person class. Where house needs the town name from town and name & phNumber from person.

Here is my code so far:

public class Town {
    protected String name;
    private int postCode;

    public Town (String tName , int tCode){
        name = tName;
        postCode = tCode;

    }

    public String getName(String name){
        return name;
    }

    public int getCode(int postCode){
        return postCode;
    }

And the person class:

public class Person {
    protected String pName;
    private long pNumber;

    public Person (String name,long number){
        pName = name;
        pNumber = number;
    }

    public String getPersonName(String name){
        return pName;
    }

    public long getNumber(long number){
        return pNumber;
    }

    public void setNumber(long newNumber){  
        pNumber = newNumber;
    }

And my house class:

public class House extends Person, Town {

    public House(String address , String name, int code , String pName,     Long pNumber) {
        this.name = Person.pName;

    }
}

But as you can see I can't seem to get the house class to do what I want, and after searching through online resources cant find much help on the matter. Any pointers in the correct direction would be much appreciated.


Solution

  • First question: What would you like to use and how? You should make your classes reflect stuff that has meaning, that makes it easier to think of how to create and use them.

    For example a House could be in a Town and contain a Person

    public class House
    {
        private Town    inTown;
        private Person  owner;
    
        public House (Town inTown, Person owner)
        {
            this.inTown = inTown;
            this.owner = owner;
        }
        public String getTownName()
        {
            return this.inTown.getName();
        }
    }
    

    Alternatively, if you really only care about the names:

    public class House
    {
        private String  townName;
        private String  ownerName;
    
        public House (Town inTown, Person owner)
        {
            this.townName = inTown.getName();
            this.ownerName = owner.getName();
        }
        public String getTownName()
        {
            return this.townName;
        }
    }
    

    If memory is not a problem, I would advice the first solution, as it is easier to extend and maintain.