2. Introduction
Java Class & Object
Key Words in OOPs
Inheritance
Polymorphism
2
Java OOPs Tutorial
Prof. K. Adisesha
3. Introduction
Prof. K. Adisesha
3
Introduction:
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
➢ It simplifies software development and maintenance by providing some concepts:
❖ Object
❖ Class
❖ Inheritance
❖ Polymorphism
❖ Abstraction
❖ Encapsulation
❖ Coupling & Cohesion
❖ Association
❖ Aggregation
❖ Composition
4. Introduction
Prof. K. Adisesha
4
OOPs Concepts in Java:
The basic concept of OOPs is to create objects, re-use them throughout the program, and
manipulate these objects to get results.
➢ Class − The class is one of the Basic concepts of OOPs which is a group of similar entities. It is
only a logical component and not the physical entity.
➢ Object - An object can be defined as an instance of a class, and there can be multiple instances of
a class in a program.
➢ Inheritance - Inheritance is one of the Basic Concepts of OOPs in which one object acquires the
properties and behaviors of the parent object.
➢ Polymorphism - Polymorphism refers to one of the OOPs concepts in Java which is the ability of
a variable, object or function to take on multiple forms.
➢ Abstraction - Abstraction is one of the OOP Concepts in Java which is an act of representing
essential features without including background details.
5. Introduction
Prof. K. Adisesha
5
OOPs Concepts in Java:
The basic concept of OOPs is to create objects, re-use them throughout the program, and
manipulate these objects to get results.
➢ Encapsulation − Encapsulation is one of the best Java OOPs concepts of wrapping the data and
code. In this OOPs concept, the variables of a class are always hidden from other classes.
➢ Association - Association is a relationship between two objects. It is one of the OOP Concepts in
Java which defines the diversity between objects. In this OOP concept, all objects have their
separate lifecycle, and there is no owner.
➢ Aggregation - In this technique, all objects have their separate lifecycle. However, there is
ownership such that child object can’t belong to another parent object.
➢ Composition - Composition is a specialized form of Aggregation. It is also called “death”
relationship. Child objects do not have their lifecycle so when parent object deletes all child
object will also delete automatically.
6. Introduction
Prof. K. Adisesha
6
Advantage of OOPs over Procedure-oriented programming language:
➢ OOPs makes development and maintenance easier, whereas, in a procedure-oriented
programming language, it is not easy to manage if code grows as project size increases.
➢ OOPs provides the ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
➢ anywhere.
➢ OOPs provides data hiding, whereas, in a procedure-oriented
programming language, global data can be accessed from
anywhere.
7. Java OOPs
Prof. K. Adisesha
7
Classes:
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
➢ A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
➢ A class in Java can contain:
❖ Fields
❖ Methods
❖ Constructors
❖ Blocks
❖ Nested class and interface
//Defining a Student class.
class Student{
int id; //field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
} }
8. Java OOPs
Prof. K. Adisesha
8
Classes:
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
➢ A class can contain any of the following variable types.
❖ Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
❖ Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
❖ Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
9. Java OOPs
Prof. K. Adisesha
9
Access modifiers:
Access modifiers public, private, protected and default affect the way the variables and
methods of the parent class are inherited by the child class.
➢ Private: Variables and methods declared private in the parent class cannot be inherited by child
classes. They can only be accessed in the parent class.
➢ Public: Variables and methods declared as public in the parent class would be inherited by the
child class and can be accessed directly by the child class.
➢ Protected: Variables and methods declared as protected in the parent class would be inherited
by the child class and can be accessed directly by the child class. But the access level is limited to
one subclass.
➢ Default: This is the case where no access modifier is specified. Variables and methods which
have default access modifiers in the parent class can be accessed by the child class.
10. Java OOPs
Prof. K. Adisesha
10
Objects :
An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class..
➢ In Java, the new keyword is used to create new objects.
➢ There are three steps when creating an object from a class −
❖ Declaration − A variable declaration with a variable name with an object type.
❖ Instantiation − The 'new' keyword is used to create the object.
❖ Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object. public static void main(String args[])
{
Student s1=new Student();
-
}
11. Java OOPs
Prof. K. Adisesha
11
Objects:
An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class..
➢ Creating an object or instance
Student s1=new Student(); //creating an object of Student
➢ There are 3 ways to initialize object in Java:
❖ By reference variable
❖ By method
❖ By constructor
//Java Program to demonstrate having the main method in another class
class Student{ //Creating Student class. .
int id;
String name; }
//Creating another class TestStudent1 containing the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name); } }
12. Java OOPs
Prof. K. Adisesha
12
Initialize object in Java:
Initialization through reference: Initializing an object means storing data into the
object.
➢ By reference variable Student s1.id= 100; //initialize an object of Student
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
//By reference variable
s1.id=100;
s1.name=“Adisesha";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
} }
13. Java OOPs
Prof. K. Adisesha
13
Initialize object in Java:
Initialization through method: Creating the objects of class and initializing the value to
these objects by invoking the method.
➢ By method s1.MethodName(v1,“v2"); //initialize By method
class Student{
int rollno; String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInfo(){System.out.println(rollno+" "+name);
}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,“Sunny”);
s2.insertRecord(222,“Prajwal");
s1.displayInfo();
s2.displayInfo();
}
14. Java OOPs
Prof. K. Adisesha
14
Initialize object by constructor:
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created.
➢ At the time of calling constructor, memory for the object is allocated in the memory.
➢ It is a special type of method which is used to initialize the object.
➢ There are two rules defined for the constructor.
❖ Constructor name must be the same as its class name
❖ A Constructor must have no explicit return type
❖ A Java constructor cannot be abstract, static, final, and synchronized
➢ There are two types of constructors in Java:
❖ Default constructor (no-arg constructor): <class_name>( ){Staements}
❖ Parameterized constructor : Student(int i,String n){
➢ Note: There is no copy constructor in Java. id = i; name = n; }
15. Java OOPs
Prof. K. Adisesha
15
Java static keyword:
The static keyword in Java is used for memory management mainly. If you declare any
variable as static, it is known as a static variable it gets memory only once in the class area
at the time of class loading.
➢ The static variable can be used to refer to the common property of all objects (which is not
unique for each object).
➢ The static can be:
❖ Variable (also known as a class variable)
❖ Method (also known as a class method)
❖ Block
❖ Nested class
16. Java OOPs
Prof. K. Adisesha
16
Java static keyword:
The static keyword in Java is used for memory management mainly. A static variable it
gets memory only once in the class area at the time of class loading.
➢ Variable (also known as a class variable): static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.
❖ It makes your program memory efficient (i.e., it saves memory).
❖ Syntax: static String college =“SJES College";//variable gets memory only once and retain its value
➢ Method (also known as a class method): If you apply static keyword with any method, it is
known as static method. class Calculate{ static int cube(int x)
{ return x*x*x; } ….. }
❖ A static method belongs to the class rather than the object of a class.
❖ A static method can be invoked without the need for creating an instance of a class.
❖ A static method can access static data member and can change the value of it.
17. Java OOPs
Prof. K. Adisesha
17
Java static keyword:
The static keyword in Java is used for memory management mainly. A static variable it
gets memory only once in the class area at the time of class loading.
➢ Static block: Is used to initialize the static data member. It is executed before the main method at
the time of class loading.
❖ Syntax:
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
} }
❖ Output: static block is invoked
Hello main
18. Java OOPs
Prof. K. Adisesha
18
this keyword in Java:
In Java, this keyword refers to the current object in a method or constructor. There can be
a lot of usage of Java this keyword.
➢ The this keyword is to eliminate the confusion between class attributes and parameters with
the same name
➢ Usage of Java this keyword
❖ Invoke current class constructor
❖ Invoke current class method
❖ Return the current class object
❖ Pass an argument in the method call
❖ Pass an argument in the constructor call
class Student{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
19. Java OOPs
Prof. K. Adisesha
19
this keyword in Java:
this: to refer current class instance variable-
➢ The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.
➢ When parameters (formal arguments) and instance variables are same. we are using this
keyword to distinguish local variable and instance variable.
➢ If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword class Student{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
class Student{
int rollno;
String name;
Student(int Reg,String Sname){
rollno= Reg;
name= Sname;
}
20. Java OOPs
Prof. K. Adisesha
20
this keyword in Java:
this: to invoke current class method-
➢ You may invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method.
21. Java OOPs
Prof. K. Adisesha
21
this keyword in Java:
this() : to invoke current class constructor-
➢ The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
Output:
hello Adisesha
10
class A{
A(){System.out.println("hello Adisesha");}
A(int x){
this();
System.out.println(x);
} }
class TestThis{
public static void main(String args[]){
A a=new A(10);
}}
22. Java OOPs
Prof. K. Adisesha
22
this keyword in Java:
this: to pass as an argument in the method-
➢ The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling.
Output:
method is invoked
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();
} }
➢ Application of this that can be passed as an argument
in event handling (or) in a situation where we have to
provide reference of a class to another one. It is used
to reuse one object in many methods.
➢ We can return this keyword as an statement from the
method. In such case, return type of the method must
be the class type (non-primitive).
➢ Syntax: return_type method_name(){
return this; }
23. Java OOPs
Prof. K. Adisesha
23
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.
➢ It can be initialized in the constructor only.
➢ Final can used in:
❖ Variable: If you make any variable as final, you cannot change the value of final variable(It will
be constant).
final int speedlimit=90;//final variable
❖ Method: If you make any method as final, you cannot override it.
final void run(){System.out.println("running");}
❖ Class: If you make any class as final, you cannot extend it.
final class Bike{}
class Bike9{
final int speedlimit=90;//final variable
void run(){ speedlimit=400; }
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output: Compile Time Error
24. Java OOPs
Prof. K. Adisesha
24
Array, Strings, Vectors in Java:
Array: An array is a block of container that can hold data of one single type. The array is
a fundamental construct in Java that allows you to store and access a large number of
values conveniently.
❖ Declare an array:
dataType[] arrayName; int[] data; //One-Dimensional Array
dataType[][] arrayName; int[][] data; //Two-Dimensional Array
➢ dataType can be a primitive data type like int, char, Double, byte, etc. arrayName is an identifier.
❖ Initializing an array:
int a[]=new int[5];
int a[][]=new int[3][3];
int a[][] = new int[2][3];
for(r=0;r< 2; r++)
{ for(c=0; c< 3; c++)
{ n = obj.readLine();
a[r][c]=Integer.parseInt(n); }
}
25. Java OOPs
Prof. K. Adisesha
25
Array, Strings, Vectors in Java:
Strings: The Array of Characters are called as the Strings They are Generally used for
representing the Strings in java String is Also Array and Also a Class.
❖ Creating an String array:
String s[]=new String[10]; String s = new String("Welcome To Strings");
➢ S is an object of Class String and now you can use any Method From String Class.
❖ Method From String Class:
int s = n.length;
string2 = string1.toLowerCase;
string2 = string1.toUpperCase;
string2 = string1.replace (‘k’, ‘i’);
static String n[] = {"Madras","Delhi","Ahmedabad","Bombay"};
{ int s = n.length;
String t =null;
for(int i=0; i < s; i++)
{ for(int j=i+1; j < s; j++)
{ if(n[j].compareTo(n[i]) < 0) //compareTo String Method
{ t = n[i]; n[i] = n[j]; n[j] = t; }
}
26. Java OOPs
Prof. K. Adisesha
26
Array, Strings, Vectors in Java:
Strings: The Various String Methods those are Reside in String Class are :-
➢ ToLowerCase:- For Converting a String into small letters or in small cases.
➢ ToUpperCase:- For Converting a String into Upper letters or in Upper cases.
➢ Length:- For Calculating the Number of Characters in a String.
➢ Trim:- For Removing both left and Right Side Spaces.
➢ charAt:- For Finding a Character at the Position.
➢ indexOf:- For Finding the Position of a Character in a String.
➢ substring:- For Extracting a string from a string.
➢ replace:- For Replacing a Character in the String.
➢ compareTo:- For Comparing a String With another.
➢ Concat:- For Joining Two strings and Making a Single String.
27. Java OOPs
Prof. K. Adisesha
27
Array, Strings, Vectors in Java:
Vector: Vector is a type of class that can be used to create a generic dynamic array that
can hold objects of any type and any number.
➢ Java Vector class comes under the java.util package.
➢ Vectors are created like arrays as follows:
Vector list=new Vector();
Vector list=new Vector(4);.
➢ Advantages of Vector:
❖ It is convenient to use vectors to store objects.
❖ A vector can be used to store a list of objects that may vary in size.
❖ We can add and delete objects from the list as and when required..
28. Java OOPs
Prof. K. Adisesha
28
Array, Strings, Vectors in Java:
Vector: Vector is a type of class that can be used to create a generic dynamic array that
can hold objects of any type and any number.
➢ Some Vector Methods are given as follows.
Vector Methods Description
list.addElement(item) It adds the item specified to the list at the end.
list.elementAt(n) It gives the name of the nth object.
list.size() It gives the number of objects present
list.removeElement(item) It removes the specified item from the list.
list.removeElementAt(n) It removes the item stored in the nth position of the list.
list.removeAllElements() It removes all the elements in the list.
list.copyInto(array) It copies all items from list to array.
list.insertElementAt(item, n) It inserts the item at nth position.
29. Java OOPs
Prof. K. Adisesha
29
Array, Strings, Vectors in Java:
Vector: Vector is a type of class that can be used to create a generic dynamic array that
can hold objects of any type and any number.
import java.io.*;
import java.util.*;
class vectorclass
{ public static void main(String args[])
{ Vector list = new Vector();
int l = args.length;
for (int i=0; i < l; i++)
{ list.addElement(args[i]); }
list.insertElementAt(“K. Adisesha",2);
int s = list.size();
String larr[]=new String[s];
list.copyInto(larr);
System.out.println("List of Elements");
for (int i=0; i < s; i++)
{ System.out.println(larr[i]); }
}
}
30. Java OOPs
Prof. K. Adisesha
30
Inheritance in Java:
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
➢ The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
➢ Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
➢ The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
➢ The extends keyword indicates for making a new class that derives from an existing class.
31. Java OOPs
Prof. K. Adisesha
31
Inheritance in Java:
Terms used in Inheritance
➢ Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
➢ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
➢ Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.
➢ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class.
32. Java OOPs
Prof. K. Adisesha
32
Inheritance in Java:
Types of inheritance in java
➢ On the basis of class, there can be three types of inheritance in java: Single, Multilevel
and Hierarchical.
➢ In java programming, multiple and hybrid inheritance is supported through interface
only.
33. Java OOPs
Prof. K. Adisesha
33
Inheritance in Java:
Single Inheritance in Java
➢ This is the simplest form of inheritance, where subclasses inherit the features of one
super class.
class SuperClass {
void methodSuper() {
System.out.println("I am a super class method");
} }
// Inheriting SuperClass to SubClass
class SubClass extends SuperClass {
void methodSubclass() {
System.out.println("I am a sub class method");
} }
class Main
{
public static void main(String args[])
{
SubClass obj = new SubClass();
obj.methodSubClass();
obj.methodSuper();
}
} Output:
I am a sub class method
I am a super class method
34. Java OOPs
Prof. K. Adisesha
34
Multilevel Inheritance in Java:
➢ This is an extension to single inheritance in java, where another class again inherits the
subclass, which inherits the superclass.
class SuperClass {
void methodSuper() {
System.out.println("I am a super class method");
} }
// Inheriting SuperClass to SubClass1
class SubClass1 extends SuperClass {
void methodSubclass() {
System.out.println("I am a sub class1 method");
} }
// Inheriting SubClass1 to SubClass2
class SubClass2 extends SubClass1
{
void methodSubclass() {
System.out.println("I am a sub class2 method");
} }
class Main {
public static void main(String args[])
{ SubClass2 obj = new SubClass2();
obj.methodSub2Class();
obj.methodSub1Class();
obj.methodSuper();
} }
Output:
I am a sub class2 method
I am a sub class1 method
I am a super class method
35. Java OOPs
Prof. K. Adisesha
35
Hierarchical Inheritance in Java:
➢ In this inheritance, a single superclass is inherited separately by two or more subclasses.
class SuperClass {
void methodSuper() {
System.out.println("I am a super class method");
} }
// Inheriting SuperClass to SubClass1
class SubClass1 extends SuperClass {
void methodSub1class() {
System.out.println("I am a sub class1 method");
} }
// Inheriting SuperClass to SubClass2
class SubClass2 extends SuperClass {
void methodSub2class() {
System.out.println("I am a sub class2 method");
} }
class Main {
public static void main(String args[])
{ SubClass1 obj1 = new SubClass1();
SubClass2 obj2 = new SubClass2();
obj2.methodSub2Class();
obj2.methodSuper();
obj1.methodSub1Class();
obj1.methodSuper();
} }
Output:
I am a sub class2 method
I am a super class method
I am a sub class1 method
I am a super class method
36. Java OOPs
Prof. K. Adisesha
36
Java Polymorphism:
Types of inheritance in java
➢ Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
➢ Polymorphism in Java can be achieved in two ways i.e., method overloading and method
overriding.
➢ Polymorphism in Java is mainly divided into two types.
❖ Compile-time polymorphism: Achieved by method overloading
❖ Runtime polymorphism: Achieved by method overriding.
37. Java OOPs
Prof. K. Adisesha
37
Polymorphism:
Compile-time polymorphism: This type of polymorphism in Java is also called static
polymorphism or static method dispatch. It can be achieved by method overloading.
➢ In this process, an overloaded method is resolved at compile time rather than resolving
at runtime. class Parent {
// perimeter method with a single argument
static int perimeter(int a) {
return 4 * a;
}
// perimeter method with two arguments (overloading)
static int perimeter(int l, int b) {
return 2 * (l + b);
}
}
➢ Method overloading: a class can
have multiple methods of the same
name, and each method can be
differentiated either by bypassing
different types of parameters or
bypassing a different number of
parameters.
38. Java OOPs
Prof. K. Adisesha
38
Method overloading: Consider a class where multiple methods have the same name. It will be
difficult for the compiler to distinguish between every method.
class Parent {
// perimeter method with a single argument
static int Shape (int a)
{ return 4 * a; }
// perimeter method with two arguments (overloading)
static int Shape(int l, int b)
{ return 2 * (l + b); }
}
class Polymorphism {
public static void main(String[] args) {
// calling Shape method by passing a single argument
System.out.println("Side of square : 4n Perimenter of square
will be : " + Parent.Shape(4) + "n");
// calling Shape method by passing two arguments
System.out.println("Sides of rectangle are : 10, 13n
Perimeter of rectangle will be : " + Parent.Shape(10, 13)); }
}
Output:
Side of square : 4
Perimeter of square will be : 16
Sides of rectangle are : 10, 13
Perimeter of rectangle will be : 46
39. Java OOPs
Prof. K. Adisesha
39
Polymorphism:
Runtime Polymorphism: Runtime polymorphism is also called Dynamic method dispatch.
Instead of resolving the overridden method at compile-time, it is resolved at runtime.
➢ Runtime polymorphism in Java occurs when we have two or more classes, and all are
interrelated through inheritance.
➢ Method overriding: If a child class has a method as its parent class, it is called method
overriding.
➢ Rules for overriding a method in Java
❖ There must be inheritance between classes.
❖ The method between the classes must be the same(name of the class, number, and
type of arguments must be the same).
40. Java OOPs
Prof. K. Adisesha
40
Method overriding: If a child class has a method as its parent class, it is called method
overriding.
// parent class Shape
class Shape{
// creating area method
void area(){
System.out.println("Formula for areas.");
}
}
// Square class extends Shape class
class Square extends Shape{
// overriding area method
void area(){
System.out.println("Area of square : a * a");
}
}
// Rectangle class extends Shape class
class Rectangle extends Shape{
// overriding area method
void area(){
System.out.println("Area of rectangle : 2 * (a + b)");
}
}
// Circle class extends Shape class
class Circle extends Shape{
// overriding area method
void area(){
System.out.println("Area of circle : pi * r * r");
}
}
class Polymorphism{
public static void main(String[] args) {
// creating new object of Shape class
Shape S = new Shape();
S.area();
S = new Square();
S.area();
S = new Rectangle();
S.area();
S = new Circle();
S.area();
}
}
Output:
Formula for areas.
Area of square : a * a
Area of rectangle : 2 * (a + b)
Area of circle : pi * r * r
41. Java OOPs
Prof. K. Adisesha
41
Polymorphism:
Characteristics of Polymorphism.
➢ Besides method overloading and method overriding, polymorphism has other
characteristics as follows.
❖ Coercion :The implicit conversion of one data type into another without changing its context is
known as coercion. This type of conversion occurs to prevent type errors.
❖ Internal Operator Overloading: Java does not support operator overloading. Still, there is a
concept called internal operator overloading where an operator is used in more than one way. In
Java, the ‘+’ symbol is used to add two numbers or used to concatenate two strings.
❖ Polymorphic Variables or Parameters: Variables having different values under different
circumstances is called polymorphic variable.
❖ Subtype polymorphism: The ability to use the subclass instead of the superclass is called subtype
polymorphism.
42. Java OOPs
Prof. K. Adisesha
42
Java Abstraction:
Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or
interfaces.
➢ To access the abstract class, it must be inherited from another class.
➢ The abstract keyword is a non-access modifier, used for classes and methods:
❖ Abstract class: is a restricted class that cannot be used to create objects (to access
it, it must be inherited from another class). abstract class ClassA {…}
❖ Abstract method: can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).
// Abstract method (does not have a body)
public abstract void Method1();
43. Java OOPs
Prof. K. Adisesha
43
Java Abstraction:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).
➢ A class which contains the abstract keyword in its declaration is known as abstract class.
➢ Abstract classes may or may not contain abstract methods, i.e., methods without body ( public
void get(); )
➢ But, if a class has at least one abstract method, then the class must be declared abstract.
➢ If a class is declared abstract, it cannot be instantiated.
➢ To use an abstract class, you have to inherit it from another class, provide implementations to
the abstract methods in it.
➢ If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
44. Java OOPs
Prof. K. Adisesha
44
Java Abstraction:
Abstract Methods: If you want a class to contain a particular method but you want the
actual implementation of that method to be determined by child classes, you can
declare the method in the parent class as an abstract.
➢ abstract keyword is used to declare the method as abstract.
➢ You have to place the abstract keyword before the method name in the method declaration.
➢ An abstract method contains a method signature, but no method body.
➢ Instead of curly braces, an abstract method will have a semi colon (;) at the end.
public abstract class Employee {
private String name;
private String address;
private int number;
public abstract double Salary( );
// Remainder of class definition }
45. Java OOPs
Prof. K. Adisesha
45
Java - Encapsulation:
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.
➢ 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
➢ Benefits of Encapsulation
❖ The fields of a class can be made read-only or write-only.
❖ A class can have total control over what is stored in its fields.
46. Java OOPs
Prof. K. Adisesha
46
Java - Interfaces:
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
➢ Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.
➢ An interface is similar to a class in the following ways −
❖ An interface can contain any number of methods.
❖ An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
❖ The byte code of an interface appears in a .class file.
❖ Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name..
47. Java OOPs
Prof. K. Adisesha
47
Java - Interfaces:
Interfaces have the following properties −
➢ An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
➢ Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
➢ Methods in an interface are implicitly public.
➢ Declaring Interfaces: The interface keyword is used to declare an interface.
/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations}
}
Example
/* File name : Student.java */
interface Student {
public void Personal();
public void Course();
}
48. Java OOPs
Prof. K. Adisesha
48
Java - Interfaces:
Implementing Interfaces− When a class implements an interface, you can think of the class as
signing a contract, agreeing to perform the specific behaviors of the interface. If not the class must
declare itself as abstract.
➢ A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration..
/* File name : BCA.java */
public class BCA implements Student {
public void Personal ()
{ System.out.println(“K. ADISESHA");
}
public void Course ()
{ System.out.println(“Java Programming");
} }
public static void main(String args[])
{
BCA obj = new BCA();
obj. Personal();
obj. Course();
}
}
Output:
K. ADISESHA
Java Programming
49. Java OOPs
Prof. K. Adisesha
49
Java - Interfaces:
When overriding methods defined in interfaces, there are several rules to be followed −
➢ Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
➢ The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
➢ An implementation class itself can be abstract and if so, interface methods need not be
implemented.
➢ When implementation interfaces, there are several rules −
❖ A class can implement more than one interface at a time.
❖ A class can extend only one class, but implement many interfaces.
❖ An interface can extend another interface, in a similar way as a class can extend another
class.