Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

Most Tricky Access Modifier Protected

Loading...

Published in: Java And J2EE
878 Views

Most tricky access modifier protected

Shamik M / Kolkata

1 year of teaching experience

Qualification: B.Tech in Computer Science

Teaches: Big Data & Hadoop, Web Development, Photography, Java And J2EE, Spring Training

Contact this Tutor
  1. Understanding most critical access modifier protected in java? protected is most critical modifier to understand According to the book it is same as default modifier, which can be accessed by other classes in same package but the only difference is it can also be accessed by subclasses from outside packages through inheritance. Now there are two catch points 1. 2. 1. In a. What do you mean by accessed ? What do you mean by access through inheritance? What do you mean by accessed ? java you can access properties of other classes by two ways Association (HAS A) 2. inheritance (IS A) Scenario a. packge com.foo; public class Foo extends Bar Bar bar new Bar(); // BAR HAS A relationship with FOO(Association) bar . greet; // not compile no visibility through association package com.bar; public class Bar protected String greet - Scenario b packge com.foo Class Foo extends Bar System . out . println(greet); " Hello" // Inherited so it print Hello "Hello" • package com.bar Class Bar protected String Association means Scenario a. Inheritance means For protected the greet - a class has a reference of another class as you see in a class inheriting parent class property. tricky situation arises when two classes are in different package , as you see Foo is in com.foo and Bar in com.bar now the question is, can Foo access Bar's greet variable? The Answer is simply no as by rule protected is visible only through inheritance
  2. so although class Foo extends Bar but we are trying to access greet by association which is not acceptable in java On other hand in Scenario 2 will be compile fine and show Hello message as Foo inherited Bar's greet property. Now add another criticality suppose class zoo is in the packge com.foo now If I write following code snippet in Zoo Foo foo new Foo(); foo. greet; will it be compile? Think about it The Answer is no as I said earlier by Association (different package ) you can't ever access greet. but in Same package you do.