• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inheritance thru upcasted reference

 
william kane
Ranch Hand
Posts: 260
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BaseClass bc = new DerivedClass();
bc.protectedMethod();
In the above given code the BaseClass is the parent of derived class and protectedMethod is protected in Base Class
And this code is placed in a instance method of the derived class.
Why do i get a compiler error ........ " Can't access protected method protectedMehod in BaseClass. BaseClass is not a subclass of the current class." ?
please explain.........

------------------
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, it's a bit like forums, really. Say that Java in General (beginner) is the base class, and Java in General (intermediate) the subclass. Articles are like private methods, so that if you post a question in beginner (the base class), you cannot post the same question in intermediate (the subclass). If you do, people like myself will waste their time answering questions which have been perfectly adequately answered in another forum. Thank you.
- Peter
PS. Ditto for subsubclasses, of course, like Java in General (advanced). You really know how to illustrate a point, don't you?
 
william kane
Ranch Hand
Posts: 260
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats what inheritance is all about right if u can provide a better implementation(answer) the user always has choice as the which implementation to use.......
I was not aware of that rule anyway..............
 
Fred Hosch
Author
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, since there is no overriding going on here, the
fact that bc refers to a DerivedClass instance at run time is a
red herring. it has no relevance at all. the static type of bc
is BaseClass.
Second, the lrm state that a protected member may be accessed from outside the package only by code "responsible for the implementation of the object." That means that dc.protectedMember() can appear in the definition of BaseClass
or of DerivedClass (where dc is declared to be of type DerivedClass), but bc.protectedMember() cannot appear in DerivedClass, UNLESS DerivedClass and BaseClass are in the same package.
is this a major KLUDGE? imho, yes it is.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
William, you might want to read our FAQ, which covers this and other issues. I'm closing this thread (and the one in Intermediate) to prevent addtional wasted effort by the various people who might reply.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic