• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance heirarchy

 
Sophie Angela
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class base
{
String s="jai";
Object o=s;
Object k=new Object();
String h=(String)o;
String s=o;/* can this be done? */
}
In the above coding.what is the difference between objects o and k.What will be the pointing.?Can i cast the object o to a string?If so what will be the contents of the objects o and h..?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...Can i cast the object o to a string?If so what will be the contents of the objects o and h..?
What happened when you compiled/ tried to execute your code. The quickest way to find out if something can be done is to try and do it.
 
Chetan Raju
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.

First of all, there are two problems with your code.
1. You are declaring String variable s twice which will fail compilation.
2. You are trying to assign a wider type of var to a narrower type which will again fail at compilation.

According to java rules, you cannot assign a broader type variable to narrower type variable. In this case you are trying to assing s=o where s is a String and o is an object which is a superclass of String. Although "o" contains a string but it is illegal to assign it to String type without a type cast.

In the 2nd line, Object o=s, you are assigning a String (which is also an object) to an Object which is perfectly legal.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic