Lecture 4
Outline
• Java Encapsulation
• Nested classes
• Inner Classes
• Accessing Private Members
• Method-local Inner Class
• Anonymous Inner Class
• Java - Inheritance
1
Java Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation, the variables of a
class will be hidden from other classes, and can be accessed only through the methods
of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
• Declare the variables of a class as private.
• Provide public setter and getter methods to modify and view the variables
values.
Example
Following is an example that demonstrates how to achieve Encapsulation in Java :
/* File name : EncapTest.java */
public class EncapTest {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
2
}
public void setIdNum( String newId) {
idNum = newId;
}
}
The public setXXX() and getXXX() methods are the access points of the instance
variables of the EncapTest class. Normally, these methods are referred as getters and
setters. Therefore, any class that wants to access the variables should access them
through these getters and setters.
The variables of the EncapTest class can be accessed using the following program :
/* File name : RunEncap.java */
public class RunEncap {
public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("Nader");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
}
}
This will produce the following result :
Name : Nader Age : 20
3
Nested Classes
In Java, just like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java. The class written within is called
the nested class, and the class that holds the inner class is called the outer class.
Syntax
Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer
class and the class Inner_Demo is the nested class.
class Outer_Demo {
class Inner_Demo {
}
}
Nested classes are divided into two types :
• Non-static nested classes − These are the non-static members of a class.
• Static nested classes − These are the static members of a class.
Non-static Nested Classes
4
Inner Classes (Non-static)
Inner classes are a security mechanism in Java. We know a class cannot be associated
with the access modifier private, but if we have the class as a member of other class,
then the inner class can be made private. And this is also used to access the private
members of a class.
Inner classes (Non-static Nested Classes) are of three types depending on how and
where you define them. They are:
• Inner Class
• Method-local Inner Class
• Anonymous Inner Class
Inner Class
Creating an inner class is quite simple. You just need to write a class within a class.
Unlike a class, an inner class can be private and once you declare an inner class private,
it cannot be accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example,
we make the inner class private and access the class through a method.
5
Example
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}
}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner class,
and this method is invoked from the main method.
If you compile and execute the above program, you will get the following result −
Output
This is an inner class.
6
Accessing the Private Members
As mentioned earlier, inner classes are also used to access the private members of a
class. Suppose, a class is having private members to access them. Write an inner class
in it, return the private members from a method within the inner class, say, getValue(),
and finally from another class (from which you want to access the private members)
call the getValue() method of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter,
using the object of the outer class, following is the way in which you can instantiate the
inner class.
Outer_Demo outer = new Outer_Demo();
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
The following program shows how to access the private members of a class using inner
class.
Example
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
7
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
If you compile and execute the above program, you will get the following result :
Output
This is the getnum method of the inner class:
175
Method-local Inner Class
In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner
class is defined. The following program shows how to use a method-local inner class.
Example
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;
// method-local inner class
class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
8
} // end of inner class
// Accessing the inner class
MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.my_Method();
}
}
If you compile and execute the above program, you will get the following result :
Output
This is method inner class 23
Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class.
In case of anonymous inner classes, we declare and instantiate them at the same time.
Generally, they are used whenever you need to override the method of a class or an
interface. The syntax of an anonymous inner class is as follows :
Syntax
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
The following program shows how to override the method of a class using anonymous
inner class.
9
Example
abstract class AnonymousInner {
public abstract void mymethod();
}
public class Outer_class {
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is an example of anonymous inner class
Static Nested Class:
A static inner class is a nested class which is a static member of the outer class. It can
be accessed without instantiating the outer class, using other static members. Just like
static members, a static nested class does not have access to the instance variables and
methods of the outer class. The syntax of static nested class is as follows −
Syntax
class MyOuter {
static class Nested_Demo {
}
}
Instantiating a static nested class is a bit different from instantiating an inner class. The
following program shows how to use a static nested class.
10
Example
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}
public static void main(String args[]) {
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is my nested class
Java - Inheritance
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance, the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
11
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax
of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
class A {
}
class B extends A {
A: super class B: subclass
Example
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
12
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x , int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
After executing the program, it will produce the following result :
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
13
The Superclass reference variable can hold the subclass object, but using that variable
you can access only the members of the superclass, so to access the members of both
classes it is recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But
using the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested classes) from
its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
• It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
• It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables we
use super keyword as shown below.
super.variable
super.method();
Sample Code
In the given program, you have two classes namely Sub_class and Super_class, both
have a method named display() with different implementations, and a variable named
14
num with different values. We are invoking display() method of both classes and
printing the value of the variable num of both classes. Here you can observe that we
have used super keyword to differentiate the members of superclass from subclass.
Example
class Super_class {
int num = 20;
// display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
}
}
public class Sub_class extends Super_class {
int num = 10;
// display method of sub class
public void display() {
System.out.println("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class
sub.display();
// Invoking the display() method of superclass
super.display();
// printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);
// printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:"+ super.num);
}
public static void main(String args[]) {
Sub_class obj = new Sub_class();
15
obj.my_method();
}
}
Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically
acquires the default constructor of the superclass. But if you want to call a
parameterized constructor of the superclass, you need to use the super keyword as
shown below.
super(values);
Sample Code
The program given in this section demonstrates how to use the super keyword to invoke
the parametrized constructor of the superclass. This program contains a superclass and
a subclass, where the superclass contains a parameterized constructor which accepts
an integer value, and we used the super keyword to invoke the parameterized
constructor of the superclass.
Copy and paste the following program in a file with the name Subclass.java
16
Example:
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String args[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}
Output
The value of the variable named age in super class is: 24
17
Types of Inheritance:
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple inheritance.
This means that a class cannot extend more than one class. Therefore following is
illegal :
Example
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which has helped Java get
rid of the impossibility of multiple inheritance.
18