Search code examples
javainheritanceabstractsubclassing

Accessing Subclass Methods and Instances From Within a Method With A Superclass Parameter


Novice Java programmer here...

So I have this superclass:

public abstract class Animal
{

    public abstract String attack(Animal entity);

}

and then I have this subclass:

public class Dog extends Animal
{

    protected int something;

    public int getSomething()
    {
        return something;
    }

    @Override
    public String attack(Animal entity)
    {
        entity.getSomething();
        //THIS RIGHT HERE
    }

I'm not asking why this isn't working as much as I'm asking how I would go about accessing those methods and instances within that subclass. Should I create a new instance of Dog within the attack method and assign entity to the newly created instance? What is the "right" way to go about accomplishing this?


Solution

  • What you are trying to do is to invoke the method getSomething() on an instance of class Animal in your implementation of the attack(Animal entity) method.

    This clearly can't work, because this method is not defined for class Animal. I believe you want that the dog can attack any type of animal and vice versa. What you have to do then is to add the method to the Animal:

    public abstract class Animal {       
        public abstract String getSomething();
        //rest
    }
    

    Then you clearly have to override the method in every subclass of animal. Or, if possible in your use case, at the attribute to the animal class and implement the getSomething() method directly there:

    public abstract class Animal {  
        private String something;
        public String getSomething() {
            return this.something;
        }
        //rest
    }
    

    Please think again about the visibility protected of your attribute. If something is protected, than every instance of classes in the same package can access and modify it without the getter.