Module 2 Notes New
Module 2 Notes New
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.
1
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
2
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as
of Employee class i.e. code reusability.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
3
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
4
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
5
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
6
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.
class A
{
void msg()
{
System.out.println("Hello");
}
}
class B
{
void msg()
{
System.out.println("Welcome");
}
7
}
class C extends A,B
{
//suppose if it were
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
8
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
Output:
9
Java method overriding is mostly used in Runtime Polymorphism.
10
}
Output
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
11
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables , methods, blocks and nested classes . The static keyword belongs to
the class than an instance of the class.
o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
12
Advantages of static variable
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.
13
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
14
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.
class Counter
{
int count=0;//will get memory each time when the instance is created
Counter()
{
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[])
{
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
1
1
15
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
16
{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}
OUTPUT
Compile Time Error
17
3) Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
18
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
19
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
Output:
20
class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
Output:
hello n
hello m
class A
{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
21
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}
}
Output:
hello a
10
class Student
{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course)
{
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee)
{
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class TestThis7
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
22
s2.display();
}
}
Output:
class S2
{
void m(S2 obj)
{
System.out.println("method is invoked");
}
void p()
{
m(this);
}
public static void main(String args[])
{
S2 s1 = new S2();
s1.p();
}
}
Output:
method is invoked
23
class B
{
A4 obj;
B(A4 obj)
{
this.obj=obj;
}
void display()
{
System.out.println(obj.data);//using data member of A4 class
}
}
class A4
{
int data=10;
A4()
{
B b=new B(this);
b.display();
}
public static void main(String args[])
{
A4 a=new A4();
}
}
Output:10
return_type method_name()
{
return this;
}
24
Example of this keyword that you return as a statement from
the method
class A
{
A getA()
{
return this;
}
void msg()
{
System.out.println("Hello java");
}
}
class Test1
{
public static void main(String args[])
{
new A().getA().msg();
}
}
Output:
Hello java
25
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
26
1) super is used to refer immediate parent class
instance variable.
We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
Output:tay
black
white
In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.
27
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.
28
3) super is used to invoke parent class
constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
Output:
animal is created
dog is created
29
Note: super() is added in each class constructor automatically by compiler if there
is no super() or this().
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
System.out.println("dog is created");
}
}
class TestSuper4
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
Output:
animal is created
dog is created
30
super example: real use
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property,
we are using parent class constructor from child class. In such way, we are reusing the
parent class constructor.
class Person
{
int id;
String name;
Person(int id,String name)
{
this.id=id;
this.name=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display()
{
System.out.println(id+" "+name+" "+salary);
}
}
class TestSuper5
{
public static void main(String[] args)
{
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}
}
Output:
1 ankit 45000
31
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.
class Bike9
{
final int speedlimit=90;//final variable
32
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
33
3) Java final class
If you make any class as final, you cannot extend it.
34
Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Points to Remember
35
Example of abstract class
36
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.
Output
running safely
Mostly, we don't know about the implementation class (which is hidden to the end
user), and an object of the implementation class is provided by the factory method.
In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
37
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1
{
public static void main(String args[])
{
//In a real scenario, object is provided through method, e.g., getShape() method
Shape s=new Circle1();
s.draw();
}
}
Output
drawing circle
38
Another example of Abstract class in java
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Output
39
Abstract class having constructor, data member and
methods
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.
40
Output
bike is created
running safely..
gear changed
class Bike12
{
abstract void run();
}
Rule: If you are extending an abstract class that has an abstract method, you must either
provide the implementation of the method or make this class abstract.
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java
In other words, you can say that interfaces can have abstract methods and variables.
It cannot have a method body.
41
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.
42
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
43
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output
Hello
44
Drawable d=new Circle();//In real scenario, object is provided by metho
d e.g. / getDrawable()
d.draw();
}
}
Output:
drawing circle
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
45
}
Output:
ROI: 9.15
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
46
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
Welcome
interface Printable
{
void print();
}
interface Showable
{
void print();
}
Output:
Hello
47
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class TestTnterface1, so there is no
ambiguity.
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
Output:
Hello
Welcome
48
Q) What is marker or tagged interface?
An interface which has no member is known as a marker or tagged interface, for
example, Serializable, Cloneable, Remote, etc. They are used to provide some essential
information to the JVM so that JVM may perform some useful operation.
But there are many differences between abstract class and interface that are given
below.
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
49
6) An abstract class can extend another An interface can extend another Java interface
Java class and implement multiple Java only.
interfaces.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A
{
public void c()
{
System.out.println("I am C");
}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest of t
he methods
50
class M extends B
{
public void a()
{
System.out.println("I am a");
}
public void b()
{
System.out.println("I am b");
}
public void d()
{
System.out.println("I am d");
}
}
Output:
I am a
I am b
I am c
I am d
51
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means many
forms.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known
as upcasting. For example:
52
class A
{
}
class B extends A
{
}
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For
Example:
interface I
{
}
class A
{
}
class B extends A implements I
{
}
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
class Bike
{
void run()
{
System.out.println("running");
}
}
class Splendor extends Bike
{
53
void run()
{
System.out.println("running safely with 60km");
}
Output:
Note: This example is also given in method overriding but there was no upcasting.
class Bank
{
float getRateOfInterest()
{
return 0;
}
}
class SBI extends Bank
{
54
float getRateOfInterest()
{
return 8.4f;
}
}
class ICICI extends Bank
{
float getRateOfInterest()
{
return 7.3f;
}
}
class AXIS extends Bank
{
float getRateOfInterest()
{
return 9.7f;
}
}
class TestPolymorphism
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
Output:
55
Java Runtime Polymorphism with Multilevel
Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating fruits");
}
}
class BabyDog extends Dog
{
void eat()
{
System.out.println("drinking milk");
}
public static void main(String args[])
{
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output:
eating
eating fruits
drinking Milk
56
Static Binding and Dynamic Binding
Understanding Type
Let's understand the type of instance.
int data=30;
57
Here data variable is a type of int.
class Animal
{
}
static binding
When type of the object is determined at compiled time(by the compiler), it is known
as static binding. If there is any private, final or static method in a class, there is static
binding.
58
public static void main(String args[])
{
Dog d1=new Dog();
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
class Animal
{
void eat()
{
System.out.println("animal is eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Animal a=new Dog();
a.eat();
}
}
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the
instance of Dog is also an instance of Animal. So compiler doesn't know its type, only its base
type.
59
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
60
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
How to compile java package?
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . rep
folder.
61
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not sub packages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
62
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
63
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import
the subpackage as well.
64
Note: Sequence of the program must be package then import then class.
65
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.
To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:
Output:Welcome to package
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
66
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.
67
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
68
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package
but through inheritance only.
69
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
//save by A.java
70
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
71