Java SE(Core java)
Lecture-26
Today’s Agenda
01 Access Modifiers or Visibility Modes
02 Using Static import
03 Solving ambiguity in packages
05
Access Modifiers or
Visibility modes
Access modifier
private public default protected
Place of access
Same class Yes Yes Yes Yes
Non sub class same No Yes Yes Yes
package
Sub class same No Yes Yes Yes
package
Non sub class and No Yes No No
Different package
Sub class and Differ- No Yes No Yes
ent package
Method Overriding and
Visibility modes
• When we override methods of base class in the derived class, then access modifiers
play an important role and Java forces programmers to follow a particular rule.
• Rule is that, while overriding a method of base class in its derived class either we
can keep the same access modifier or we can use less restrictive access modifier.
• For example, if a method is in default visibility in base class then while overriding it
we can make it protected or public but we cannot make it private.
Using static import
• This feature was added from Java 5.
• This features facilitates Java programmer to use static members directly without
using its class name.
• Its only advantage is less coding is required to access the static members of the
class.
• Let us see an example to understand this…
Example
import java.lang.System.*;
class Test
{
public static void main(String [ ] args)
{
out.println(“Hello User !”);
}
}
Using static import
• Only available for static members of the class. We cannot use it for non static
members of the class.
• If a local member is present with the same name as that of the static member, then
the local member overlaps the static member.
• If two static members of different class have the same name, then in this case using
them directly will create an syntax error.
Solving ambiguity in Packages
package p1; package p2; import p1.*;
class Student class Student import p2.Student;
{ { class Test
----- ----- {
----- ----- p s v main(String [ ] args)
----- ----- {
----- ----- Student s=new Student( );
} } -----
-----
-----
}
Solving ambiguity in Packages
• Named import has greater precedence over wild card import i.e. import done using *.
• If both the classes are imported using named import then the only solution to this
ambiguity is creating objects along with package name.
• Example, p1.Student s=new p1.Student( );
Thank you