Reputation: 71
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
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
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
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