• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected Access Modifier question

 
Jude Niroshan
Ranch Hand
Posts: 132
5
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy Everyone!

This is very basic question. I'm down the way to get my first oracle certification. Currently I'm reading OCA exam guide. I was reading about protected access modifier. So, I wrote this simple example to understand it clearly. I am working on eclipse Kepler.

Below is my Parent class (ProtectedTest.java)


Below is my child class (Test.java)

Note : I don't have anything other than main() in my child class

I get a ClassCastException. Why is that? Ohh, another question, why do I need to explicitly do the cast? Is casting forcing by Eclipse (IDE) ?

I know many of you ranchers feel this is very basic Java, just forgive me and help me with this.
Thank you!
 
salvin francis
Bartender
Posts: 1339
11
Eclipse IDE Google Web Toolkit Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I request you to paste actual code next time instead of pictures.

Take a look at your inheritance structure. As per classification rules, a superclass reference can point to a subclass object and not the other way around
Eg:
You don't need a class casting here.

An example of a class casting would be ...

 
Jude Niroshan
Ranch Hand
Posts: 132
5
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay. I figured it out.

I was trying to cast a Animal to a Dog. Ohhh, c'mon. that's not fair. who the hell are we? we are Cats! I'm not a bloody Dog. watchout!
Not every Animal is a Dog.So I can't cast a Parent to a Child. Down-cast is not allowed in Java. So, that's why I got ClassCastException.

So, I should change my Child class as follows :

protected modifier has nothing to do with that. Anyways, if I have a protected field, accessibility of that would depend on the reference what I hold, Am I correct?
Because If I have below; it won't work. As for the exam guide, it states that Parent is not extending Parent. Therefore Parent class reference cannot call a protected field on parent class.
 
salvin francis
Bartender
Posts: 1339
11
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:
protected modifier has nothing to do with that.

Correct, it falls under inheritance.

Jude Niroshan wrote:
Anyways, if I have a protected field, accessibility of that would depend on the reference what I hold, Am I correct?

I dont understand what you mean here.

But here is my stand on protected modifier:
A protected modifier is helpful from the inheritance point of view, so a subclass can access it. This gives it an advantage over private modifiers. Its not public, its not private, its simply protected, open for extension by a subclass. I may be wrong here, but a subclass may even elevate a method for example to public


 
salvin francis
Bartender
Posts: 1339
11
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:As for the exam guide, it states that Parent is not extending Parent. Therefore Parent class reference cannot call a protected field on parent class.

Are you sure ? Even if it does, don't use parent/child terminology with inheritance. Its a classification and not biological inheritance. A subclass inherits all properties of its super class and adds much more.
 
Jude Niroshan
Ranch Hand
Posts: 132
5
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi francis,
Appreciate your replies.
Jude Niroshan wrote:

Anyways, if I have a protected field, accessibility of that would depend on the reference what I hold, Am I correct?

I dont understand what you mean here.


Correct me if I'm still wrong.

Protected modifier = default(same package) visibility + subClass accessibility.

But accessing protected method or a variable can be taken place under only inside a SubClass or the same class itself(Class we declared our protected methods and variables).
 
salvin francis
Bartender
Posts: 1339
11
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is my correction :
Protected modifier is equivalent to default(same package) visibility and subClass accessibility.

That equals and plus sign don't look logical from a concept point of view.

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

If I were to write it in my words...
While the default modifier (aka no modifier/package-private modifier) allows accessing from the same class as well as classes in the same package,
The protected modifier allows accessing from the same class, same package as well as from a subclass in a different package.
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:I'm down the way to get my first oracle certification.

Excellent decision!

Jude Niroshan wrote:Currently I'm reading OCA exam guide.

Which OCA study guide are you using?

Jude Niroshan wrote:I was reading about protected access modifier. So, I wrote this simple example to understand it clearly.

That's an excellent attitude! You should always write small code snippets to get a better understanding of all concepts. Because you can't learn a new programming language by just reading a book, you have to get your hands dirty

Jude Niroshan wrote:I am working on eclipse Kepler.

It's recommended (certainly if you are new to Java) to not use an IDE while preparing for the certification exam. You should use your favourite text editor, javac and java. Here you can read different opinions (with pros and cons) about using an IDE in your certification exam preparation.

Jude Niroshan wrote:Below is my Parent class (ProtectedTest.java)
Below is my child class (Test.java)

Why do you post code snippets as screenshots and not the plain code snippets (and you should of course UseCodeTags )? If I want to compile (and execute) your code snippets, I know have to type them myself. So I'll be losing precious time which I could otherwise be spending on typing a nice reply...

Jude Niroshan wrote:I get a ClassCastException. Why is that?

You already have figured out why you get a ClassCastException: you are trying to convert an Animal into a Dog but not all animals are dogs (you have cats, lions, bumblebees, and so on).

Jude Niroshan wrote:Ohh, another question, why do I need to explicitly do the cast? Is casting forcing by Eclipse (IDE) ?

To convince the compiler you know what you are doing. It's not forced by the IDE. If you would use your favourite text editor and javac, you'll get a similar compiler as well. You can't assign an object of a superclass to a reference variable of a subclass, because not every superclass object (animal) IS-A subclass (dog). And with a cast you are telling to the compiler that you know what you are doing and the compiler should treat this superclass object (animal) as a subclass (dog). And as you have already experienced, this can be dangerous. If you try to cast an object to an incompatible type, you'll get a ClassCastException. Use the instanceof operator to verify if a cast will be valid and you avoid this runtime exception from being thrown.

Jude Niroshan wrote:I know many of you ranchers feel this is very basic Java, just forgive me and help me with this.

No need to apologize. We are all here to learn!

Hope it helps!
Kind regards,
Roel
 
Jude Niroshan
Ranch Hand
Posts: 132
5
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As always Roel, much pleased with your posts. I am reading jeanne boyarsky's Java 8 OCA exam guide book. Sorry for posting the code in images. Next time I won't. I feel this post is not a good one. Would you mind if I make this resolved? Because I don't want to put garbage in this awesome forum.

Thank you again.
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:So, I should change my Child class as follows :

Please note that the above code will only successfully compile, because this code is in the main() method defined in the Test class itself. If it would have been in another class (in the org.test package), you would get a compiler error on the second line. If you would have used ProtectedTest p1 = new ProtectedTest(); on the first line, you'll get a compiler error on the second line as well. And that's because of the protected access modifier of the doSomething() method. Illustrated in this adjusted and extended code snippetTime for a little pop quiz: can you explain for each lineX the reason why the code compiles successfully or you'll get a compiler error?

I think this post and this one have both excellent explanations about the protected access modifier. And this thread shows how changing the access modifier of a method can change the output.

Hope it helps!
Kind regards,
Roel
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
salvin francis wrote:A subclass inherits all properties of its super class and adds much more.

That's (of course) not 100% correct! The private members (properties and methods) of a superclass are never inherited by a subclass.
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:Correct me if I'm still wrong.

Protected modifier = default(same package) visibility + subClass accessibility.

As a reminder think of default = package-private and protected = package-private + kids. If the subclass is in a different package, then you can only access a protected member from its superclass by inheritance (not using a reference variable of the superclass), as illustrated in the code snippet of this post.
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:I feel this post is not a good one. Would you mind if I make this resolved? Because I don't want to put garbage in this awesome forum.

Marking a thread as resolved just shows your questions/doubts were answered/cleared, it doesn't make the thread disappear So if you feel your questions were answered and your doubts were cleared, feel free to mark it to be resolved But the thread won't disappear doing so. For the record: I don't think this thread is garbage, understanding the protected access modifier can be very tricky. So many other ranchers might benefit from your questions/doubts and the given explanations.
 
salvin francis
Bartender
Posts: 1339
11
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
salvin francis wrote:A subclass inherits all properties of its super class and adds much more.

That's (of course) not 100% correct! The private members (properties and methods) of a superclass are never inherited by a subclass.

Darn !! I keep forgetting about private. Its like they don't exist
 
Jude Niroshan
Ranch Hand
Posts: 132
5
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Roel,
This is the best part I like on your posts. Free sample questions!

You put the hardest one as the very first question. All your commented results are correct. (I didn't try it by typing, but I try to be the compiler as I'm going to face for OCA exam near future)
Child object has assigned to a Parent type reference which is completely Ok. But doSomething() is not accessible using that Parent type reference. If that reference would have been ProtectedSub type, we will be able to access that doSomething() . That change is actually the method2()

protected members are visible for child classes. Therefore, no problem at all when accessing protected members on first level parents. But we can't access grand-parent's protected members. (Actually this example doesn't have grand-parent class)

Just used super keyword. Other than that it's the same like method3()

ProtectedTest is exists in a different package. Also it is not even extending from ProtectedSuper Parent class. Therefore there is no way to access any protected members of ProtectedSuper class inside the ProtectedTest class.

Thanks Roel for your quiz. I really loved it. It was actually productive!
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:This is the best part I like on your posts. Free sample questions!

Maybe I should open a PayPal account and charge a few bucks

Jude Niroshan wrote:All your commented results are correct.

That was my intention

Jude Niroshan wrote:(I didn't try it by typing, but I try to be the compiler as I'm going to face for OCA exam near future)

That's indeed what you should be doing each time. After you have answered each of them, you could of course always check for yourself using javac (and java) as well.

Jude Niroshan wrote:method1()
Child object has assigned to a Parent type reference which is completely Ok. But doSomething() is not accessible using that Parent type reference.

You are correct! doSomething() can not be accessed using a reference variable of the superclass type, it can only be accessed through inheritance. So you'll get a compiler error.

Jude Niroshan wrote:If that reference would have been ProtectedSub type, we will be able to access that doSomething() . That change is actually the method2()

But why can you access doSomething() using a reference variable of the subclass type (and not with the superclass type)? Because it's said that you can access a protected method only through inheritance, but in method2() we are using a reference variable and it compiles successfully

Jude Niroshan wrote:method3() protected members are visible for child classes. Therefore, no problem at all when accessing protected members on first level parents. But we can't access grand-parent's protected members. (Actually this example doesn't have grand-parent class)

Are you sure about the first-level parents and grand-parent's protected members? Where have you read about this rule? Let's verify these statements by adding a grandchild class to the example. So yet another pop quiz Can you explain for each methodX the reason if the code compiles successfully or not? And why (not)?

Jude Niroshan wrote:method4() Just used super keyword. Other than that it's the same like method3()

True! method3() and method4() are equivalent to each other.

Jude Niroshan wrote:ProtectedTest is exists in a different package. Also it is not even extending from ProtectedSuper Parent class. Therefore there is no way to access any protected members of ProtectedSuper class inside the ProtectedTest class.

Spot-on!

Hope it helps!
Kind regards,
Roel
 
Jude Niroshan
Ranch Hand
Posts: 132
5
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


methodA() - does not compile. Trying to access a protected method resides in a different package.

methodB() - does not compile. Accessing protected members via a reference can only be done if the parent is also in the same package where the class we use reference variable.

methodC() - compiles okay. Used the advantage of Inheritance. doSomething() protected method is available inside ProtectedSubSub. So, using a reference of that type or just can directly access that method.(My assumption was wrong! proved from this one!)

methodD / E() - inheritance gave the permission to directly access the protected members.

This was really a tough one. Thanks again.
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jude Niroshan wrote:methodA() - does not compile. Trying to access a protected method resides in a different package.

It indeed doesn't compile, but the explanation is incomplete. In methodC(), methodD(), and methodE() a protected method (defined in a class in a different package) is accessed/invoked without any problem.

Jude Niroshan wrote:methodB() - does not compile. Accessing protected members via a reference can only be done if the parent is also in the same package where the class we use reference variable.

Correct! methodB() doesn't compile. But again the explanation is incorrect. In methodC() a protected member is accessed via a reference variable while the class defining the protected member is defined in another package.

Jude Niroshan wrote:methodC() - compiles okay. Used the advantage of Inheritance. doSomething() protected method is available inside ProtectedSubSub. So, using a reference of that type or just can directly access that method.(My assumption was wrong! proved from this one!)

True! Because the doSomething() method is protected, it's available in any subclass of the ProtectedSuper class and ProtectedSubSub IS-A ProtectedSuper. In a subclass an inherited protected method behaves like a private method. Mark my words: I said "behaves" not "is". And that's why you can invoke the doSomething() method using a reference variable of type ProtectedSubSub inside a method defined in the ProtectedSubSub class.

Jude Niroshan wrote:methodD / E() - inheritance gave the permission to directly access the protected members.



Hope it helps!
Kind regards,
Roel
 
nick woodward
Ranch Hand
Posts: 370
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


quick question, couldn't see the answer......

why was this allowed? I thought (and as you said Roel) protected access is through inheritance only?

good thread though

Nick

** edit:: nevermind, I see it now
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nick woodward wrote:** edit:: nevermind, I see it now

And what have you seen? Just to verify you have found the correct reason.
 
nick woodward
Ranch Hand
Posts: 370
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
nick woodward wrote:** edit:: nevermind, I see it now

And what have you seen? Just to verify you have found the correct reason.


the difference between line 26 and line 12, so the fact that the code resides in the subclass itself? (therefore the method is inherited, despite access by dot notation)


and Jude - I read casts like they are 'promises' to the compiler. Test p1 = (I promise this is a Test) new ProtectedTest();

i don't know if that helps you, but it helps me see more clearly that a) it's not a 'Test' object, and b) it compiles but fails at runtime. Which also helps me remember ClassCastException is a runtime exception!

(i hope that's correct!!)

Regards,

Nick
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nick woodward wrote:the difference between line 26 and line 12, so the fact that the code resides in the subclass itself? (therefore the method is inherited, despite access by dot notation)

True! Because the doSomething() method is protected, it's available in any subclass of the ProtectedSuper class and ProtectedSub IS-A ProtectedSuper. In a subclass an inherited protected method behaves like a private method. Mark my words: I said "behaves" not "is". And that's why you can invoke the doSomething() method using a reference variable of type ProtectedSub inside a method defined in the ProtectedSub class.
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nick woodward wrote:and Jude - I read casts like they are 'promises' to the compiler. Test p1 = (I promise this is a Test) new ProtectedTest();

That's exactly what casting is all about

It's like you telling the compiler: "Hey man, I know this is not the type you were expecting, but don't be afraid I'm a true professional and I know what I'm doing so please treat this object as this type and stop your whining/complaining".
And then the compiler replies: "Ok man, you are the professional, you know what you are doing; so I'll be happy to stop whining/complaining and compile this code for you".
And then the application is executed and the JVM kicks in: "Oh no, again a guy who thought he was a true professional but in fact he's a complete moron! ProtectedTest IS-NOT-A Test. So I'll be throwing a ClassCastException right in his face. Mwaaaaahahahaha!"

nick woodward wrote:(i hope that's correct!!)

It definitely is. In this thread you'll find an explanation about a similar code snippet. And also links to other topics related with casting. Definitely worth reading!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic