3

Using the following code:

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

public class Cat extends Animal {   
    public void a() {
        System.out.println("Cat");
    }
}

public class BlackCat extends Cat {
    public static void main(String[] args) {

        BlackCat blackCat = new BlackCat();
        blackCat.a();
    }
}

How to use in child class BlackCat method a() from Animal but not from Cat?
I want to receive Animal in console.

nmyk
  • 1,582
  • 1
  • 8
  • 20
Bohdan Myslyvchuk
  • 1,657
  • 3
  • 24
  • 39

1 Answers1

1

I guess you could add an addition function with a set prefix (this case _) and use that as your "super accessor" or what ever you want to call it.

public class Cat extends Animal {   
    public void a() {
        System.out.println("Cat");
    }
    public void _a() {
        super.a();
    }
}
Olian04
  • 6,480
  • 2
  • 27
  • 54
  • Thank you for your comment. But the question is could I use directly method from parent class for hierarchy directly? without changing Animal and Cat class. I suppose I'm not allowed to do that. – Bohdan Myslyvchuk Aug 09 '16 at 08:51
  • 1
    @BohdanMyslyvchuk no, not if your object doesn´t represent an actuall class `Animal`. If you´d be able to do so you´d break the rules of polymorphism – SomeJavaGuy Aug 09 '16 at 08:53
  • 1
    @BohdanMyslyvchuk no I'm sorry, in your example the method a() in Cat is [overriding](https://docs.oracle.com/javase/tutorial/java/IandI/override.html) the method a() in Animal. Its a part of the [polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) in java. – Olian04 Aug 09 '16 at 08:53
  • For more detail read this http://stackoverflow.com/questions/3456177/calling-super-super-class-method – CrazyJavaLearner Aug 09 '16 at 08:56