• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

reference casting

 
Ranch Hand
Posts: 290
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class fruit
{
public void popo1()
{
System.out.println("this is a popo1 of the fruit class");
}
}
interface squeezable
{
}
class citrus extends fruit
{
public void popo()
{
System.out.println("this is a popo method of the citrus class");
}
}
class lemon extends citrus
{
}
class grapefruit extends citrus
{
public void nitin()
{
System.out.println("what r u trying to do");
}
}
class tangelo extends citrus
{

}
class popo
{
}
class lapore
{
public static void main(String[]args)
{
grapefruit g[]=new grapefruit[50];
for(int i=0;i<g.length;i++)>
{
g[i]=new grapefruit();
}
citrus[] s=g;
for(int i=0;i<s.length;i++)>
{
s[i].nitin();
}
/*grapefruit[] a=(grapefruit[])s;
for(int i=0;i<a.length;i++)>
{
a[i].nitin();
}*/
}
}
In the above example i have assigned the reference of the subclass to the base class.Then from the base class(citrus)array variable i tried to invoke the
method nitin(),I expected an error but it's showing an output.The reason why i expected an error is that we can invoke a subclass method through the reference varaible of the superclass only if superclass contain's the method with the same name.That is when overriding come's into picture.
Please throw some light on it.
------------------
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Nitin,
If the base class does not contain that method you will get a compiler error.
This code <pre>

class Base {
void methodOne(){}
}
class Derived extends Base{
void methodTwo(){}
}
public class Test {
public static void main(String[] args){
Base x = new Derived();
x.methodTwo();
}
}
</pre>
Will give you an error because Base does not have methodTwo.
Hope this helps.
Cheers
Sahir
http://www.geocities.com/sahirshah/
 
nitin sharma
Ranch Hand
Posts: 290
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi everybody
get some solution for me.Waiting for the reply?
 
reply
    Bookmark Topic Watch Topic
  • New Topic