aspose file tools*
The moose likes Beginning Java and the fly likes Dynamic assignment of an Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic assignment of an Array" Watch "Dynamic assignment of an Array" New topic
Author

Dynamic assignment of an Array

Poorna Nandam
Greenhorn

Joined: Apr 01, 2009
Posts: 20
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

Joined: Oct 13, 2005
Posts: 39393
    
  28
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

Joined: Apr 01, 2009
Posts: 20
Thank a lot............................

Poorna Nandam
Greenhorn

Joined: Apr 01, 2009
Posts: 20


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


salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 928

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"

My Website: [Salvin.in] Cool your mind:[Salvin.in/painting] My Sally:[Salvin.in/sally]
Poorna Nandam
Greenhorn

Joined: Apr 01, 2009
Posts: 20
Thank you salvin,


BR
Poorna
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
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

Joined: Apr 01, 2009
Posts: 20
Output would be



Thank you,
Poorna
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dynamic assignment of an Array