Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding

 
vendikonda sravan
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can Some buddy explain why the out put is coming as " sub 2010" for the Fallowing classes

public abstract class A
{
int i=20;
abstract void a();
public static void main(String[] args)
{
System.out.println("Hello World!");
}
public int a2(){
System.out.print("super");
return i;}
}



public class C extends A
{
int i =10 ;

public static void main(String[] args)
{
A x= new C();
System.out.print(x.i+""+x.a2());
}
public void a(){}
public int a2(){
System.out.print("sub");
return i;
}
}
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vendikonda sravan wrote: the out put is coming as " sub 2010"


but i think it should be 10sub20............not what you said
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
phil sohar wrote:
vendikonda sravan wrote: the out put is coming as " sub 2010"


but i think it should be 10sub20............not what you said


yes you are right .........actually in this.......print statement runs from right to left
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When the System.out command runs, it first evaluates the x.a2() expression. This
causes 'sub' to be printed. It then prints the 'i' value associated with the type of
variable 'x' (type A) followed by the return value of the x.a2() expression. The " "
is needed in the print argument to assure that the + operator adds strings rather
than integers.

Jim ... ...
 
vendikonda sravan
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks jim
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic