File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic assignment of an Array

 
Poorna Nandam
Greenhorn
Posts: 20
  • 0
  • 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
Pie
Posts: 47253
52
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank a lot............................

 
Poorna Nandam
Greenhorn
Posts: 20
  • 0
  • 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
Pie
Posts: 1227
10
Eclipse IDE Google Web Toolkit Java
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you salvin,


BR
Poorna
 
Campbell Ritchie
Sheriff
Pie
Posts: 47253
52
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Output would be



Thank you,
Poorna
 
Campbell Ritchie
Sheriff
Pie
Posts: 47253
52
  • 0
  • 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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic