LSM
LSM

Reputation: 135

Java parent class using child class attributes

public animal{

        String name;
        String species;

        public introduction(){
                System.out.println("Hi, my name is" + name +", i am a " + species);
        }
}

public dog extends animal{
        String species = "dog";
}

I am wondering if i were to build more child classes like cat, bird etc, with with their unique species variable. If there a way whereby I can make them self-introduce different according to their species?

I understand that I am asking a parent class to access a child-class attribute, which seems to defeat the purpose of inheritance in the first place, but I am not sure what is a more elegant way of doing this.

Upvotes: 0

Views: 4054

Answers (1)

papaya
papaya

Reputation: 1535

Based on your animal.class you already seem to have defined a public member variable name and species. This is obviously part of the child classes namely cat.class and dog.class

Your parent class has syntax errors function should return void like so:

public void introduction(){
       System.out.println("Hi, my name is" + name +", i am a " + species);
}

Your child classes would look like this:

class Cat extends Animal{
 
  public Cat(){
    super.name = "tom"
    super.species = "cat"
  }

}

class Mouse extends Animal{
 
  public Mouse(){
    super.name = "jerry" //simply calling name = "jerry" will work as this is inherited.
    super.species = "mouse"
  }

}

Note that I haven't child level member variables, and you can call them like so:

Animal cat = new Cat();
Animal mouse = new Mouse();

cat.introduction(); // prints Hi, my name is tom...
mouse.introduction(); //prints Hi, my name is jerry ... 

Also, it is a good practise to follow Programming guidelines as CamelCasing your classes. eg(Animal instead of animal)

Upvotes: 1

Related Questions