Results 1 to 3 of 3
Thread: Checking class of object
- 12-06-2010, 10:48 AM #1
Member
- Join Date
- Dec 2010
- Posts
- 13
- Rep Power
- 0
Checking class of object
I've a following piece of code which generates an error for which I don't understand.. Would appreciate some help
Error:Java Code:public class DoggyCheck{ public static void main(String[] args) { // Spaniel is a subclass of Dog Spaniel pet = new Spaniel ("Duffus"); Dog aDogPet; // Check if pet is class/subclass of Dog if(pet instanceof Dog) System.out.println("We have a dog!"); else System.out.println("It's definitely not a dog!"); // Check if pet is the exact class Dog (FAIL) if(pet.getClass() == Dog.class) System.out.println("We have a dog!"); else System.out.println("It's definitely not a dog!"); } }
DoggyCheck.java:12: incomparable types: java.lang.Class<capture#639 of ? extends Spaniel> and java.lang.Class<Dog>
if(pet.getClass() == Dog.class)
- 12-06-2010, 11:02 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,408
- Blog Entries
- 7
- Rep Power
- 17
The compiler is trying to be smart, i.e. it 'knows' that pet is a Spaniel so its class can never be a Dog.class and it triumphantically starts to whine. Do that test in another method so the compiler loses track of the actual class of the object:
kind regards,Java Code:class Dog { public Dog(String name) { } } class Spaniel extends Dog { public Spaniel(String name) { super(name); } } public class T { private static void check(Object o) { if(o.getClass() == Dog.class) System.out.println("We have a dog!"); else System.out.println("It's definitely not a dog!"); } public static void main(String[] args) { // Spaniel is a subclass of Dog Spaniel pet = new Spaniel ("Duffus"); Dog aDogPet; // Check if pet is class/subclass of Dog if(pet instanceof Dog) System.out.println("We have a dog!"); else System.out.println("It's definitely not a dog!"); // Check if pet is the exact class Dog (FAIL) check(pet); } }
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-06-2010, 12:34 PM #3
Member
- Join Date
- Dec 2010
- Posts
- 13
- Rep Power
- 0
Similar Threads
-
Create object of unknown class, based on existing object
By Zack in forum New To JavaReplies: 2Last Post: 06-22-2010, 04:29 AM -
add object to ArrayList (object is from extends other class)
By mBull in forum Java AppletsReplies: 3Last Post: 03-15-2010, 08:44 PM -
object vs class
By billq in forum New To JavaReplies: 5Last Post: 12-24-2009, 04:56 PM -
Getting name of object class
By Java Tip in forum Java TipReplies: 0Last Post: 11-05-2007, 05:22 PM -
Creating object of Type Object class
By venkatv in forum New To JavaReplies: 3Last Post: 07-17-2007, 03:33 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks