简体   繁体   English

如何设置条件语句来检查在 java 中调用方法的 object 的类型是什么

[英]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.

相关问题 如何嵌套此条件语句? 在Java中 - How can I nest this conditional statement? in Java 如何将方法的返回类型指定为调用方法的对象的类型? - How can I specify as return type of a method the type of the object upon which the method is called? 如何检查Java映射包含的数据类型? - How can I check what type of data a java map contains? 如何强制Java为方法调用的参数之一接受条件类型? - How can I force Java to accept a conditional type for one of the parameters of a method call? 如何为带有传递给方法的参数的catch语句设置预期的Exception类型? - How can I set the the expected Exception type for a catch statement with a parameter I've passed into a method? 如何检查是否已在Java中创建/调用过对象? (Eclipse IDE) - How can I check if an object has been created/called upon in Java? (Eclipse IDE) 在Java中调用的这种方法覆盖是什么? - What is this type of method overriding called in Java? Java中条件语句scope如何返回object? - How to return object in conditional statement scope in Java? 我可以在 Java 的 if 语句中有 3 个条件语句吗? - Can I have 3 conditional statements in an if statement in Java? 如何在Java的IF语句中检查方法是返回true还是false? - How do I check if a method returns true or false in an IF statement in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM