• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Protected method visibility

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
-------------Code----------------------------------------------------
package bindaas1;

public class Animal {

protected void eat() {
System.out.println("Animals prefer idali vada");
}
}

package bindaas2;
import bindaas1.Animal;

class Dog extends Animal {

}


public class Beagal extends Dog{

public static void main(String ... args) {
Dog d1 = new Beagal(); // Line 1
d1.eat();// Line 2
((Beagal)d1)).eat(); // Wroks ??? - Line 3
}
}
-----------------------------------------------------------

in the above code Line 2 does not compile. This is fine as eat() method is protected and available only in child class Dog. But Why Line 3 compiles fine ? d1 is casted int Beagal. But protected is not visible below one child level. Then how it compiles ?

Thanks in advance.
[ March 17, 2007: Message edited by: Ramesh J ]
 
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Child passes "IS-A Parent" test then, that child can access protected memebers of Parent.
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried the above scenario (1 top class with a protected method, 2 subclasses) and the grandchild subclass had no problem executing the top level protected method without any casting.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic