0
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.

0

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

4 Comments

You don't need super in the constructor. The field is already inherited
I know, I assumed OP is new to java and didn't want to confuse him/her
I have tried using this.name = "Tom" & this.species = "cat", but did not work; is it because the keyword this by default assign the value to the child-level attribute? and using super will assign the value to the parent attribute? Is that correct?
Your parent class variables must be public or protected to be inherited, if you don’t explicitly say it’s packaged private but public within the package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.