This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confused with Object help plz

 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Program 1:

public class hello
{

public void sayHello()
{
System.out.println("Hello");
}

public static void main(String[] args) throws Exception
{
hello instanceOfhello = new hello();
instanceOfhello.sayHello();
}
}

output :
Hello

Program 2:

public class hello
{

public void sayHello()
{
System.out.println("Hello");
}

public static void main(String[] args) throws Exception
{
Class c = Class.forName("hello");
Object obj = c.newInstance();
obj.sayHello();
}
}

Program 1 works fine but program 2 shout at me.....i dont know what went wrong here can anyone help me out plz
 
Raymond Ong
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by S Thanigaivel:
Program 1:

public class hello
{

public void sayHello()
{
System.out.println("Hello");
}

public static void main(String[] args) throws Exception
{
hello instanceOfhello = new hello();
instanceOfhello.sayHello();
}
}

output :
Hello

Program 2:

public class hello
{

public void sayHello()
{
System.out.println("Hello");
}

public static void main(String[] args) throws Exception
{
Class c = Class.forName("hello");
Object obj = c.newInstance();
obj.sayHello();
}
}

Program 1 works fine but program 2 shout at me.....i dont know what went wrong here can anyone help me out plz


By default, every class is a decendant of Object, but in this case, for you to call "sayHello", cast the obj to "hello" class explicitly.
 
Sujith Kanaparthi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Thanigaivel,

The program 2 is shouting at because you have not type casted the object properly. c.newInstance() returns an object but this object has to be type casted explictly to "hello" object. So your program should be as below:


Class c = Class.forName("hello");
hello obj = (hello)c.newInstance();
obj.sayHello();

Regards
Sujith
 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It works now

Thank You Mr.Raymond Ong
 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Sujith following codes works well now

Class c = Class.forName("hello");
Object obj1 = c.newInstance();
((hello)obj1).sayHello();

hello obj = (hello)c.newInstance();
obj.sayHello();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic