Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic assignment of an Array

 
Poorna Nandam
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI All,

I am new java Ranch. Can any body explain me the following code.

public class A{

private String runNow(){
return "High";
}

static class B extends A{
public String runNow(){
return "Low";
}
}

public static void main(String args[]){
A[] a=new B[]{new B(),new C()};
for(A aa:a)
System.out.print(aa.runNow()+" ");
}

}


class C extends A.B{

public String runNow(){
return "Out";
}

}
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code button; it makes your code easier to read.

We don't simply give out answers, so it would help if you answer these three questions:
What output did you expect? What output did you get? Have you any ideas why?
 
Poorna Nandam
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank a lot............................

 
Poorna Nandam
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


As you told me that , i want to know the above Array assignment.
Thanks in advance.


 
salvin francis
Bartender
Posts: 1268
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am going to give you hints:



can be written as:




Actually even the class cast is not important in this case, but thats my way of saying that it will behave like "A"
 
Poorna Nandam
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you salvin,


BR
Poorna
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was a useful hint. Now, remembering the question is really about inheritance not arrays, what do you think the output would be?
 
Poorna Nandam
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Output would be



Thank you,
Poorna
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried it? That is what happened, so your suggestion is correct.
Now please explain why you are not using polymorphism when you are calling instance methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic