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
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 :-)
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");
}
}
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();
}
}
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.
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();
}
}
Few suggestions :
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();
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");
}
Don't override super class method in child class. Always super class method is invoked.
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
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();
}
}
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();
}
}
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()
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.
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
public class superA {
public void display() {
System.out.println("In super class superA");
}
}
public class subB extends superA {
#Override
public void display() {
System.out.println("In sub class subB");
}
}
public class subC extends superA {
#Override
public void display() {
System.out.println("In sub class subC");
}
}
If an object of sub class subB calls display method, it should give output like:
(new line)In super class superA
(new line)In sub class subB
The method names of all the classes parent and child is same, when you want to override superclass/parent class method with same name in child class you have to use super keyword.
public class superA {
public void display() {
System.out.println("\nIn super class superA");
}
}
public class subB extends superA {
#Override
public void display() {
super.display();
System.out.println("\nIn sub class subB");
}
}
public class subC extends superA {
#Override
public void display() {
super.display();
System.out.println("\nIn sub class subC");
}
}
I tried to implement a function in a base class which using the function of the childs (defiend as a abstract function in the base class). I think an example will demonstrate the problem in the best way.
abstract class Animal{
public void doSomthing(){
this.sound();
}
protected abstract void sound();
}
class Dog extends Animal{
#Override
protected void sound(){
System.out.println("WAF");
}
}
now when I tried to get the element in run time (by factory method which looks like: Animal factory method("Dog);) and call to the doSomthing method I got exception because it goes to the abstract method, my question is if there is any way the bypass this or another solution for this problem.
class myMain
{
public static void main(String[]args)
{
Animal doggo = new Dog(); // create object for dog
doggo.animalSound(); // call the sound for dog
}
}
class Animal
{
public void animalSound()
{
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal
{
public void animalSound()
{
System.out.println("The Dog Says bow wow! ");
}
}
I do not see any problem with the approach you have mentioned in the description of your question. Maybe you are doing some other mistake. Check the following working code:
abstract class Animal {
public void doSomthing() {
sound();
}
protected abstract void sound();
}
class Dog extends Animal {
#Override
protected void sound() {
System.out.println("WAF");
}
}
class AnimalFactory {
static Animal animal;
public static Animal factoryMethod(String animalName) {
if ("Dog".equals(animalName)) {
animal = new Dog();
}
return animal;
}
}
class Main {
public static void main(String[] args) {
Animal animal = AnimalFactory.factoryMethod("Dog");
animal.sound();
}
}
Output:
WAF
The call to child class method from super class can be done.
Refer code snippet mentioned in below link:
Can a Parent call Child Class methods?
interface Y {
void search(String name);
}
class A implements Y {
void search(String name) {
//Is it possible to say: "If I was called from class B then do a search("B");
}
}
class B extends A {
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search();
}
}
Given the above code is it possible to reason in superclass which subclass was used for calling a method?
The reason I want to do this is because the code in Search is very similar for all Subclasses, the only thing that changes is the Classname, so I thought there is no need to Override in each subclass. I have updated the code to reflect this. Please let me know if there is a better way of doing it/
Calling this.getClass() inside your search method will give you the concrete class of the current instance.
For example:
class Example
{
static class A {
public void search() {
System.out.println(getClass());
}
}
static class B extends A {}
public static void main (String[] args) throws java.lang.Exception
{
new A().search();
new B().search();
}
}
outputs
class Example$A
class Example$B
The cleanest way to do it is to override the method in each subclass.
interface Y {
void search();
}
class A implements Y {
public void search(){
search("A");
}
protected void search(String name) {
// implement your searching algoithm here
}
}
class B extends A {
public void search(){
search("B");
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search();
}
}
That's the way inheritance is suppose to works. A super class should not know its subclasses.
And, in case you extends your class B, you can easily either:
-Keep the same behaviour as B:
class C extends B {
// do nothing, when calling search, it calls the method implemented in B
}
-Change the behaviour to search for "C"
class C extends B {
public void search(){
search("C"); // or search("whateveryouwant")
}
}
You can simply override the method in class B.
The other way could be to write the search() method as
void search() {
if (this.getClass().equals(B.class)) {
//The logic for B
} else if (this.getClass().equals(A.class)) {
//The logic for A
}
}
You have to provide the fully qualified name for the class.
Better follow template pattern.
interface Y {
void search(String name);
}
abstract class AbstractionTemplate implements Y{
#Override
public void search(String name) {
//a lot of code.
System.out.println("common stuff start");
doImplspecificStuffOnly();
System.out.println("common stuff end");
//a lot of code.
}
abstract void doImplspecificStuffOnly();
}
class A extends AbstractionTemplate{
#Override
void doImplspecificStuffOnly() {
System.out.println("a's stuff");
}
}
class B extends A {
#Override
void doImplspecificStuffOnly() {
System.out.println("B's stuff");
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search("hey");
}
}
Having issue in Java,
we can call class methods like
interface samp{
public void printMsg();
}
ClassA implements samp{
public void printMsg()
{
S.o.p("Hi ClassA");
}
}
ClassB implements samp{
public void printMsg()
{
S.o.p("Hi ClassB");
}
}
public MainClass{
public static void main(String args())
{
samp s= new ClassA();
s.printMsg();
samp s= new ClassB();
s.printMsg();
}
}
we can do this, am having different type of class method not similar methods for all classes but I want to implement the future is it possible to do? is any other pattern for this, pls help me to find this.
like
ClassA{
public void fun1(){..}
public void fun2(){..}
}
ClassB{
public void fun3(){..}
public void fun4(){..}
}
want to call these methods using a single refrence, need to asign object to that refrence dynamically is it possible friends?...
Thanks in advance
You cant do that using common interface.You can only call the method which is defined in interface using an interface reference type, even though the object it points to belong to another class have different other methods.
you can call only those class function which are defined in interface because its reference can access only those functions. ex:
interface samp{
public void printMsg();
}
ClassA implements samp{
public void printMsg()
{
S.o.p("Hi ClassA");
}
public void newmthd(){
S.o.p("you can't call me from samp reference.");
}
}
ClassB implements samp{
public void printMsg()
{
S.o.p("Hi ClassB");
}
}
public MainClass{
public static void main(String args())
{
samp s= new ClassA();
s.printMsg();
s.newmthd() //error... s don't have any knowledge of this function.
samp s= new ClassB();
s.printMsg();
}
}
Define all the methods you want your reference to have in an a superclass, but leave the implementations empty. Then, create your subclass and override the necessary methods.
Example:
Class MySuperClass {
public void fun1() {}
public void fun2() {}
public void fun3() {}
public void fun4() {}
}
Class ClassA extends MySuperClass {
public void fun1() { //implementation details }
public void fun2() { //implementation details }
}
Class ClassB extends MySuperClass {
public void fun3() { //implementation details }
public void fun4() { //implementation details }
}
public Class Tester {
public static void main(String[] args) {
MySuperClass class1 = new ClassA();
MySuperClass class2 = new ClassB();
}
}