Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes Printing Class Name Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Printing Class Name" Watch "Printing Class Name" New topic
Author

Printing Class Name

Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176

Hello everyone,

I'm having a problem in printing the class names when inheriting and I'm pretty sure the solution is fairly simple.. To better explain myself, here is a sample code:



So to write the class names of Dog and Cat I am overriding the method type(). This is incorrect (well at least for what I'm trying to do it's incorrect). I want the classes Dog and Cat to inherit a method that allows them to print their type. How can I do this?

Thanks is advance


Olly
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1753
    
    7

Olivier Legat wrote:Hello everyone,

I'm having a problem in printing the class names when inheriting and I'm pretty sure the solution is fairly simple.. To better explain myself, here is a sample code:

-code-

So to write the class names of Dog and Cat I am overriding the method type(). This is incorrect (well at least for what I'm trying to do it's incorrect). I want the classes Dog and Cat to inherit a method that allows them to print their type. How can I do this?

Thanks is advance


You can use the java.lang.Object#getClass() method to get at an Object's class at runtime.
If you take a look at API of java.lang.Class, I'm sure you can come up with a way to get at the information you're after.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874



How about overriding toString() method for each of your classes . I can see you want a retrun String after all .
Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176

Thank you Jelle and Balu, problem solved
 
Consider Paul's rocket mass heater.
 
subject: Printing Class Name
 
Similar Threads
invalid cast exception
Doubt Example
Reg. casting from Khalid Mughal
difference between redefining and overriding
Creating Objects