Results 1 to 7 of 7
Thread: confused code
- 06-30-2007, 06:33 PM #1
Member
- Join Date
- Jun 2007
- Posts
- 11
- Rep Power
- 0
confused code
Can anyone explain abt the output of this code..
class A
{
int x=1;
public void show()
{
System.out.print("hello");
}
}
public class B extends A
{
int x=2;
public void show()
{
System.out.println("hi");
}
public static void main(String args[])
{
A a;
B b=new B();
a=b;
a.show();
System.out.println(a.x);
}
}
- 07-01-2007, 07:43 AM #2
First of all it gives the following output:
hi
1
When you declare a with "A a;", you define a object pointer of type A. So whatever this object pointer points is a type of A and considered to be an A. Actually if you try to assign some other object which does not inherent from A, compiler will return an error.
So in the following line, when you assign b to a with "a=b;", b object is considered to be an instance of A and when you access x variable, the compiler gets its value from A object.
What do you think?
- 07-01-2007, 03:52 PM #3
Member
- Join Date
- Jun 2007
- Posts
- 11
- Rep Power
- 0
Then y doesn't it print "hello"
- 07-01-2007, 04:31 PM #4Then y doesn't it print "hello"
- 07-02-2007, 05:13 PM #5
Member
- Join Date
- Jun 2007
- Posts
- 11
- Rep Power
- 0
Its the rule of INHERITANCE
- 07-02-2007, 05:58 PM #6Its the rule of INHERITANCE
- 07-02-2007, 08:10 PM #7
Member
- Join Date
- Jun 2007
- Posts
- 11
- Rep Power
- 0
Similar Threads
-
[SOLVED] Confused by the textField
By jamesfrize in forum New To JavaReplies: 4Last Post: 03-28-2008, 05:30 PM -
a lot confused
By vineethraj in forum New To JavaReplies: 4Last Post: 01-18-2008, 12:36 AM -
what does it mean:confused:
By sivasayanth in forum New To JavaReplies: 2Last Post: 01-12-2008, 04:52 AM -
Java confused over Generics?
By Bibendum in forum New To JavaReplies: 3Last Post: 12-26-2007, 06:23 AM -
bit confused on this question
By money123 in forum New To JavaReplies: 2Last Post: 07-27-2007, 12:14 PM
Bookmarks