[英]How can I set a conditional statement to check what's the type of the object that called a method in java
I have in my main class an instance of an object from another class (class name's dog) (which is a child class of another one) that's calling a method from its super class (whose name's animal), and I want that method, located in the super class, to verify what's the object's type that is making the call, like the code below. I have in my main class an instance of an object from another class (class name's dog) (which is a child class of another one) that's calling a method from its super class (whose name's animal), and I want that method, located在超级 class 中,验证进行调用的对象类型是什么,如下面的代码。 Is there a way to do that?有没有办法做到这一点?
public class Main {
Dog dog = new Dog();
dog.sleep();
}
class Dog extends Animal{}
class Animal {
int size;
String color;
double weight;
void sleep(){
THIS IS HOW I WANTED IT TO WORK:
if (calling object is of type "dog" == true){
System.out.println("Dog is Sleeping");
}
void run(){
System.out.println("Running");
}
}
class Animal {
int size;
String color;
double weight;
void sleep(){
System.out.println("Running");
}
void run(){
System.out.println("Running");
}
}
class Dog extends Animal{
void sleep(){
System.out.println("Dog is sleeping.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.