Java PPT - 2 by Adi
Java PPT - 2 by Adi
Unit-2
Dr. K ADISESHA
Java OOPs Tutorial 2
Introduction
Inheritance
Polymorphism
Prof. K. Adisesha
3
Introduction
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
Prof. K. Adisesha
4
Introduction
Prof. K. Adisesha
7
Java OOPs
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: //Defining a Student class.
class Student{
❖ Fields int id; //field or data member or instance variable
❖ Methods String name;
❖ Constructors //creating main method inside the Student class
public static void main(String args[]){
❖ Blocks Student s1=new Student(); //creating an object of Student
❖ Nested class and interface //Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
Prof. K. Adisesha } }
8
Java OOPs
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.
Prof. K. Adisesha
9
Java OOPs
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.
Prof. K. Adisesha
10
Java OOPs
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();
-
Prof. K. Adisesha
}
11
Java OOPs
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:
//Java Program to demonstrate having the main method in another class
❖ By reference variable class Student{ //Creating Student class. .
❖ By method int id;
❖ By constructor 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);
Prof. K. Adisesha System.out.println(s1.name); } }
12
Java OOPs
Prof. K. Adisesha
16
Java OOPs
Prof. K. Adisesha
21
Java OOPs
Prof. K. Adisesha
28
Java OOPs
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.
Prof. K. Adisesha
31
Java OOPs
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.
Prof. K. Adisesha
32
Java OOPs
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.
Prof. K. Adisesha
33
Java OOPs
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 { class Main
void methodSuper() { {
System.out.println("I am a super class method"); public static void main(String args[])
}} {
SubClass obj = new SubClass();
// Inheriting SuperClass to SubClass obj.methodSubClass();
class SubClass extends SuperClass { obj.methodSuper();
void methodSubclass() { }
System.out.println("I am a sub class method"); } Output:
} } I am a sub class method
I am a super class method
Prof. K. Adisesha
34
Java OOPs
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.
Prof. K. Adisesha
37
Java OOPs
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 {
➢ Method overloading: a class can // perimeter method with a single argument
static int perimeter(int a) {
have multiple methods of the same
return 4 * a;
name, and each method can be }
differentiated either by bypassing // perimeter method with two arguments (overloading)
different types of parameters or static int perimeter(int l, int b) {
bypassing a different number of return 2 * (l + b);
}
parameters.
Prof. K. Adisesha }
38
Java OOPs
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 { // calling Shape method by passing a single argument
// perimeter method with a single argument System.out.println("Side of square : 4\n Perimenter of square
static int Shape (int a) will be : " + Parent.Shape(4) + "\n");
{ return 4 * a; }
// calling Shape method by passing two arguments
// perimeter method with two arguments (overloading)
System.out.println("Sides of rectangle are : 10, 13\n
static int Shape(int l, int b) Perimeter of rectangle will be : " + Parent.Shape(10, 13)); }
{ return 2 * (l + b); } }
} Output:
Side of square : 4
class Polymorphism { Perimeter of square will be : 16
public static void main(String[] args) { Sides of rectangle are : 10, 13
Prof. K. Adisesha Perimeter of rectangle will be : 46
39
Java OOPs
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).
Prof. K. Adisesha
40
Java OOPs
Method overriding: If a child class has a method as its parent class, it is called method
overriding.
// parent class Shape // Circle class extends Shape class
class Shape{ class Circle extends Shape{
// creating area method // overriding area method
void area(){ void area(){
System.out.println("Formula for areas."); System.out.println("Area of circle : pi * r * r");
} }
} }
// Square class extends Shape class class Polymorphism{
class Square extends Shape{ public static void main(String[] args) {
// overriding area method // creating new object of Shape class
void area(){ Shape S = new Shape();
System.out.println("Area of square : a * a"); S.area();
} S = new Square(); Output:
} S.area();
// Rectangle class extends Shape class S = new Rectangle();
Formula for areas.
class Rectangle extends Shape{ S.area(); Area of square : a * a
// overriding area method S = new Circle();
void area(){ S.area();
Area of rectangle : 2 * (a + b)
System.out.println("Area of rectangle : 2 * (a + b)"); } Area of circle : pi * r * r
}
Prof. K. Adisesha
}
}
41
Java OOPs
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.
Prof. K. Adisesha
42
Java OOPs
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)
Prof. K. Adisesha public abstract void Method1();
43
Java OOPs
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.
Prof. K. Adisesha
44
Java OOPs
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( );
Prof. K. Adisesha // Remainder of class definition }
45
Java OOPs
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.
Prof. K. Adisesha
46
Java OOPs
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..
Prof. K. Adisesha
47
Java OOPs
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 */ Example
import java.lang.*;
/* File name : Student.java */
// Any number of import statements
interface Student {
public interface NameOfInterface {
public void Personal();
// Any number of final, static fields
public void Course();
// Any number of abstract method declarations}
}
}
Prof. K. Adisesha
48
Java OOPs
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 static void main(String args[])
public class BCA implements Student { {
public void Personal () BCA obj = new BCA();
{ System.out.println(“K. ADISESHA"); obj. Personal();
} obj. Course();
public void Course () } Output:
{ System.out.println(“Java Programming"); } K. ADISESHA
} } Java Programming
Prof. K. Adisesha
49
Java OOPs
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.
Prof. K. Adisesha
50
Discussion
Queries ?
Prof. K. Adisesha
9449081542