Hisham Muneer
Hisham Muneer

Reputation: 8742

How to call the overridden method of a superclass?

How can I call the eat and drink method of the Animal class with the myAnimal instance in the code?

public class Animal {
    public void eat() {
        System.out.println("Animal Eats");
    }

    public void drink() {
        System.out.println("Animal Drinks");
    }
}

public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cat Eats");
    }

    @Override
    public void drink() {
        System.out.println("Cat Drinks");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.eat();
        myCat.drink();

        Animal myAnimal = myCat;        
        myAnimal.eat();
        myAnimal.drink();
    }
}

Output that I am getting:

Cat Eats
Cat Drinks
Cat Eats
Cat Drinks

This is my expected output:

Cat Eats
Cat Drinks
Animal Eats
Animal Drinks

Upvotes: 59

Views: 113362

Answers (12)

ShayakSarkar
ShayakSarkar

Reputation: 51

You can do what you want with a few minor changes to your code. Naturally the methods of the Animal class have been overriden and you cannot simply access them by changing the reference type. Instead, you could slightly change the definition of the eat and drink functions as follows.

class Animal{
    public void eat(boolean randomBoolean){
        System.out.println("Animal eats");
    }
    public void drink(boolean randomBoolean){
        System.out.println("Animal drinks");
    }
}

class Cat extends Animal{
    public void eat(boolean wantOverriden){
        if(wantOverriden){
            boolean randomBooleanValue=true|false;
            super.eat(randomBooleanValue);
        }
        else{
            System.out.println("Cat eats");
        }
    }
    public void drink(boolean wantOverriden){
        if(wantOverriden){
            boolean randomBooleanValue=true|false;
            super.drink(randomBooleanValue);
        }
        else{
            System.out.println("Cat drinks");
        }
    }
}

Now you should be able to access the overriden methods of the Animal class through the Cat class object by simply passing in a boolean value indicating if you want to do so ex:

Cat c=new Cat();
c.eat(false);     //Indicating that you dont want to access the overriden method
c.drink(false);   //Indicating that you dont want to access the overriden method
c.eat(true);          //Indicating that you want to access the overriden method
c.drink(true);        //Indicating that you want to access the overriden method

Upvotes: 0

Abhishek Kumar Singh
Abhishek Kumar Singh

Reputation: 25

You can achieve what you want using the super keyword, which allows to access the overridden method.

public class Animal {
    public void eat() {
       System.out.println("Animal Eats");
    }

    public void drink() {
       System.out.println("Animal Drinks");
    }
}

 public class Cat extends Animal {

   public void eat() {
      System.out.println("Cat Eats");
   }

   public void drink() {
      System.out.println("Cat Drinks");
   }

   public void printMessage(){
     super.eat();
     super.drink();
   }

  public static void main(String[] args) {
    Cat myCat = new Cat();
    myCat.eat();
    myCat.drink();
    myCat.printMessage();
 }
}

Upvotes: 1

Vbee
Vbee

Reputation: 21

If you make methods in each class static, it should work.

public class Animal {
    public static void eat() {
        System.out.println("Animal Eats");
    }

    public static void drink() {
        System.out.println("Animal Drinks");
    }
}


public class Cat extends Animal {
    @Override
    public static void eat() {
        System.out.println("Cat Eats");
    }

    @Override
    public static void drink() {
        System.out.println("Cat Drinks");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.eat();
        myCat.drink();

        Animal myAnimal = myCat;        
        myAnimal.eat();
        myAnimal.drink();
    }
}

The above code will give the following output

Cat Eats
Cat Drinks
Animal Eats
Animal Drinks

Upvotes: 2

friednail
friednail

Reputation: 333

You can create constructor for class Animal, that takes another Animas as parameter, and creates new instance based on provided one.

public class Animal {
    //some common animal's properties
    private int weight;
    private int age;

    public Animal() {
        // empty.
    }

    public Animal(final Animal otherAnimal) {
        this.weight = otherAnimal.getWeight();
        this.age = otherAnimal.getAge();
    }

    public void eat() {
        System.out.println("Animal Eats");
    }

    public void drink() {
        System.out.println("Animal Drinks");
    }

    // setters and getters.
}

public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cat Eats");
    }

    @Override
    public void drink() {
        System.out.println("Cat Drinks");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.eat();
        myCat.drink();

        // note: myAnimal is not a Cat, it's just an Animal.
        Animal myAnimal = new Animal(myCat);         
        myAnimal.eat();
        myAnimal.drink();
    }
}

Upvotes: 3

Jimi Kimble
Jimi Kimble

Reputation: 504

Cat can't stop being a cat, even if it is an animal. Cat will eat and cat will drink in a cat's way. It might be similar to what an Animal does, which is why it overrides the method. If you want it to do what the animal does by default, don't override. You could probably do some weird stuff with reflection and make separate methods that access the parent methods such as:

public void superDrink() {
   Animal.class.getMethod("drink").invoke();
}

but that might be overkill don't you think?

Of course that probably wouldn't work since it's not static.

Upvotes: 0

cNgamba
cNgamba

Reputation: 131

public class Main {
    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.eat();
        myCat.drink();
    
        Animal myAnimal = new Animal();
        myAnimal.eat();
        myAnimal.drink();
    }
}
    
public class Animal {
    public void eat(){
        System.out.println("Animal eat() called");
    }
    public void drink(){
        System.out.println("Animal drink() called");
    }
}
    
public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cat eat() called");
    }
    
    @Override
    public void drink() {
        System.out.println("cat drink() called");
    }
}

OUTPUT:

Cat eat() called

cat drink() called

Animal eat() called

Animal drink() called

You need to create an object of the super class Animal OR another option is to use the keyword super in the child class methods e.g., super.eat() or super.drink()

Upvotes: 0

Piet van Dongen
Piet van Dongen

Reputation: 1639

This line:

Animal myAnimal = myCat;

assigns the variable myAnimal to the object myCat, which you've created before. So when you call myAnimal.eat() after that, you're actually calling the method of the original myCat object, which outputs Cat Eats.

If you want to output Animal Eats, you'll have to assign an Animal instance to a variable. So if you would do this instead:

Animal myAnimal = new Animal()

the variable myAnimal will be an instance of Animal, and thus will overwrite the previous assignment to Cat.

If you will call myAnimal.eat() after this, you're actually calling the eat() method of the Animal instance you've created, which will output Animal Eats.

Concluding: your code should read:

public class Cat extends Animal {

    @Override
    public void eat() {
        System.out.println("Cat Eats");
    }

    @Override
    public void drink() {
        System.out.println("Cat Drinks");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.eat();
        myCat.drink();

        Animal myAnimal = new Animal();        
        myAnimal.eat();
        myAnimal.drink();
    }
}

Upvotes: 9

Andrii Dzhyrma
Andrii Dzhyrma

Reputation: 351

Here you will have an option to choose which method do you want to invoke:

public class Cat extends Animal {

    public void superEat() {
        super.eat();
    }

    public void superDrink() {
        super.drink();
    }

    @Override
    public void eat() {
        System.out.println("Cat Eats");
    }

    @Override
    public void drink() {
        System.out.println("Cat Drinks");
    }
}

Upvotes: 34

Ravindra babu
Ravindra babu

Reputation: 38950

Few suggestions :

  1. Don't pass child class reference to super class and except super class method has to be invoked for overridden method. Call super class methods from super class instance.

    Animal myAnimal = new Animal();
    myAnimal.eat();
    
  2. If you want to call super class method from child class, explicitly call super class method name with super.methodName();

    public void eat() {
        super.eat();
        System.out.println("Cat Eats");
    }
    
  3. Don't override super class method in child class. Always super class method is invoked.

Upvotes: 2

tharindu_DG
tharindu_DG

Reputation: 9291

  • Access to static fields, instance fields and static methods depends on the class of reference variable and not the actual object to which the variable points to.
  • Remember that member variables are shadowed, not overridden.
  • This is opposite of what happens in the case of instance methods.
    In case of instance methods the method of the actual class of the object is called.

    class ABCD {
        int x = 10;
        static int y = 20;
    
        public String getName() {
            return "ABCD";
        }
    }
    
    class MNOP extends ABCD {
        int x = 30;
        static int y = 40;
    
        public String getName() {
            return "MNOP";
        }
    }
    
    public static void main(String[] args) {
    
      System.out.println(new MNOP().x + ", " + new MNOP().y);
    
      ABCD a = new MNOP();
      System.out.println(a.x); // 10
      System.out.println(a.y); // 20
      System.out.println(a.getName()); // MNOP
    }
    

In this example although the the object myCat is assigned to an Animal object reference, (Animal myAnimal = myCat) the Actual object is of type Cat and it behaves as it's a cat.

Hope this helps.

Upvotes: 4

TofuBeer
TofuBeer

Reputation: 61546

You cannot do what you want. The way polymorphism works is by doing what you are seeing.

Basically a cat always knows it is a cat and will always behave like a cat regardless of if you treat is as a Cat, Felis, Felinae, Felidae, Feliformia, Carnivora, Theria, Mammalia, Vertebrata, Chordata, Eumetazoa, Animalia, Animal, Object, or anything else :-)

Upvotes: 82

TofuBeer
TofuBeer

Reputation: 61546

Please don't vote on this answer... you can vote on the other one :-) This is a bad answer, but shows how you would do what you are trying to do... poorly.

public class Main
{
    public static void main(final String[] argv) 
    {        
        Child  child;
        Parent parent;

        child  = new Child();
        parent = child;

        child.a();
        parent.a();
        child.otherA();
        parent.otherA();
    }
}

class Parent
{
    public void a()
    {
        System.out.println("Parent.a()");
    }

    public void otherA()
    {
        // doesn't matter what goes here... really should be abstract
    }
}

class Child
    extends Parent
{
    @Override
    public void a()
    {
        System.out.println("Child.a()");
    }

    @Override
    public void otherA()
    {
        super.a();
    }
}

Upvotes: 0

Related Questions