Coldoe
Coldoe

Reputation: 71

How to check type of class in Java?

I'm a newbie to Java. I wrote a class with a method, which checks the Object type. I did my initial search in google and it was difficult to understand the articles available online. I would appreciate any help. I know that line if(Object == dog) doesn't work. How could I fix this?

public class dog {
    private String name;
    private String rasa;
    private int waga;

    public dog(String name, String rasa, int waga) {
        this.name = name;
        this.rasa = rasa;
        this.waga = waga;
    }
    public void printdog()
    {
        System.out.println(this.name);
        System.out.println(this.rasa);
        System.out.println(this.waga);
        if(Object() == dog)
        {
            System.out.println("dunno how to woof");
        }
    }
}

Upvotes: 2

Views: 33402

Answers (3)

abmerday
abmerday

Reputation: 79

This way you can check too.

  Dog s = new  Dog(dog, dunno, nowaga);

  if(s.getClass().equals( Dog.class))
  {
    System.out.println("dunno how to woof");
  }

Upvotes: 1

vmrvictor
vmrvictor

Reputation: 723

this.getClass() returns the class of the object.

Instance of tells you if it is of this type. In other words dog is instance of animal, dog is also instance of dog.

Upvotes: 3

YK S
YK S

Reputation: 3430

You can use instanceof keyword to check type of object in java.

For example :

public class Stack  
{
    public Stack() {

}
public static void main(String[] args){
  Stack s1 = new  Stack();
  System.out.println(s1 instanceof Stack);
}
}

In you code you can do something like this:

if(this instanceof dog)
    {
        System.out.println("dunno how to woof");
    }

Upvotes: 4

Related Questions