What is an Object Class in Java ? (java.lang.Object

Every class that you write extends the java.lang.Object class (Whether you like it or not:) ) . It contains some methods that are absolutely essential to the Object life cycle and some convenience methods. Want to see this in action ?

[java title=”HelloWorld.java” gutter=”true” highlight=”10″]
public class HelloWorld {

public static void main(String[] args) {
// TODO Auto-generated method stub
HelloWorldBrother hwb = new HelloWorldBrother();
System.out.println (hwb);
}

}

class HelloWorldBrother
{
public HelloWorldBrother ()
{
System.out.println ( "Hello World’s Brother Class is called" );
}

}

[/java]

What do you expect this program does ? Here is the output

[java title=”HelloWorld.java Output” gutter=”true” highlight=”10″]
Hello World’s Brother Class is called
com.wonder.HelloWorldBrother@19821f
[/java]

Hello World’s Brother Class (HelloWorldBrother ) is printed as a string (In this case the JVM address). But, who is converting the Class to a String ? It is the inherited Class’s (java.lang.Object) toString() method.

You can as well over-ride it by creating a new toString() method in the HelloworldBrother.java file

[java title=”HelloWorld.java Output” gutter=”true” highlight=”8-11″]
class HelloWorldBrother
{
public HelloWorldBrother ()
{
System.out.println ( "Hello World’s Brother Class is called" );
}

public String toString ()
{
return "Hello World Brother";
}

}
[/java]

What is the output when you print out the object HelloWorldBrother ?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s