0% found this document useful (0 votes)
14 views71 pages

Unit 2 Inheritence

Uploaded by

Md Anas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views71 pages

Unit 2 Inheritence

Uploaded by

Md Anas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

MLR INSTITUTE OF TECHNOLOGY

A6IT02 – Object Oriented


Programming using JAVA
Subject Handled To Subject Handled BY

Second Year Dr.P.Chinnasamy


(B.Tech-CSE) Associate Professor, MLRIT

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
UNIT – I Java Basics
 Review of Object oriented concepts, History of
Java, Java buzzwords
 JVM architecture, Data types, Variables, Scope
and life time of variables, arrays,
 operators, control statements, type
conversion and casting,
 simple java program, constructors, methods,
Static block, Static Data, Static Method ,
 String and String Buffer Classes, Using Java API
Document

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
2
2
UNIT – II Inheritance
Polymorphism, Interfaces
 INHERITANCE AND POLYMORPHISM: Basic
concepts, Types of inheritance, Member access
rules, Usage of this and Super key word,
 Method Overloading, Method overriding, Abstract
classes,
 Encapsulation, Need for encapsulation in java, Data
hiding vs Encapsulation, getter and setter methods,
Dynamic method dispatch, Usage of final keyword.
 PACKAGES AND INTERFACES: Defining package,
Access protection, importing packages, Defining
and Implementing interfaces, and Extending
interfaces

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
3
3
Why Inheritance

How you inherit a


quality or property
from your ancestor?

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
4
4
What is Inheritance
DIAL WATCH DIGITAL WATCH

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
5
5
Inheritance

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
6
6
Inheritance

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
7
7
Inheritance
 Acquiring the properties and behaviours from one
class to another class is called inheritance (or)
producing new class from already existing class is
called inheritance.
 Reusability of code is main advantage of
inheritance.
 In Java inheritance is achieved by using extends keyword.
 The properties with access specifier private cannot be
inherited.
 Properties : variables
 Behaviours : methods
 Inheritance is also known as is-a relationship means two
classes are belongs to the same hierarchy

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
8
8
Inheritance
 In the inheritance the person who is giving the
properties is called parent ,
 The person who is taking the properties is called child

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
9
9
Syntax of Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
10
10
Types of Inheritance

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
11
11
Single Inheritance
 single inheritance, subclasses inherit the
features of one superclass.

SNIPPET

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
12
12
Multilevel Inheritance
 Multilevel Inheritance, a derived class will be
inheriting a base class and as well as the
derived class also act as the base class to
other class
SNIPPET

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
13
13
Hierarchical Inheritance
 Hierarchical Inheritance, one class serves as a
superclass for more than one sub class.

SNIPPET

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
14
14
Hybrid Inheritance –
Doesn’t support in java
 It is a mix of two or more of the above types of
inheritance.
 Since java doesn’t support multiple inheritance
with classes, the hybrid inheritance is also not
possible with classes

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
15
15
Multiple Inheritance – Doesn’t
support in java
 Multiple inheritance, one class can have more
than one parent class and inherit features
from all parent classes

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
16
16
Member Access Rules

 Public:
 Members with the public access modifier are
accessible from anywhere, both within the class
hierarchy and from outside the class.
 Public members of a superclass are inherited
and can be accessed in the subclass.
 Protected:
 Members with the protected access modifier are
accessible within the same package and by
subclasses, even if they are in a different package.
 Protected members of a superclass are inherited
by the subclass.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
17
17
Member Access Rules

 default:
 If no access modifier is specified (default
access), members are accessible within the same
package but not outside of it.
 Default members of a superclass are inherited by
the subclass if they are in the same package.
 private:
 Members with the private access modifier are only
accessible within the class where they are
declared.
 Private members of a superclass are not
inherited by the subclass

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
18
18
this Keyword
 In Java, the "this" keyword is a reference to the
current object(instance) of the class in which it is
used.
 It can be used to refer to instance variables and
instance methods of the current object within that
object's scope.
 Here are a few common use cases for the "this"
keyword in Java:
 Accessing instance variables
 Calling another constructor in the same class
 Passing this for current object as an argument

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
19
19
Accessing instance variables
using this
We can use "this" to distinguish between instance
variables and method parameters or local variables
when they have the same name
class Student
{
String name;
String mobile;
Student(String name,String mobile)
{
this.name=name;
this.mobile=mobile;
}}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
20
20
Calling another constructor
in the same class using this
 When a class has multiple constructors, you can use
"this" to call another constructor from the same
class. This is useful for constructor overloading and
code reuse.
class Employee
{
private int value;

public Employee() {
this(0); // Calls the parameterized constructor with an initial value of 0
}
public Employee(int value) {
this.value = value;
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
21
21
Passing this for current
object as an argument
public class Test
{
int i=10;
public static void main(String[] args) {
Test t=new Test();
t.m1();
}
public void m1()
{
System.out.println("m1- method is calling..");
m2(this);
}
public void m2(Test t)
{
int i=100;
System.out.println("Local var i="+i);
System.out.println("Instance var i="+t.i);

MLR INSTITUTE OF TECHNOLOGY


}
22
18-Feb-24 22
super key word
 Super is a keyword in Java which is used to
 Call the Super class variable
 Call the super class methods
 Call the super class constructor
 The most common use of the super keyword is to
eliminate the confusion and ambiguity between
super classes and subclasses that have methods,
Variables with the same name.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
23
23
super key word
 If the child class and parent class has same data
members (Variables). In that case there is a
possibility of ambiguity for the JVM.
 To avoid above ambiguity we should use super
keyword inside child class

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
24
24
Example
class Parent
{
int X=100;
int Y=200;
}
class Child extends Parent
{
int X=300;
int Y=400;
public void add()
{
System.out.println("Parent class value ="+(super.X+super.Y));
System.out.println("Child class value ="+(X+Y));
}
}
class SuperDemo
{
public static void main(String[] args) {
Child c=new Child();
c.add();
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
25
25
Calling super class
methods
class Parent
{
int X=100;
int Y=200;
public int add()
{
return X+Y;
}
}
class Child extends Parent
{
int X=300;
int Y=400;
public int add()
{
return X+Y;
}
public void printResult()
{
System.out.println("Parent class vlaue:"+super.add());//Super method to call a method
System.out.println("Child class vlaue:"+add());
}
}
class Test
{
public static void main(String[] args) {
Child c=new Child();
c.printResult();
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
26
26
Calling the super class
constructor
 super() method is used to call Super class(Parent
class) constructor.
 super() method call must be inside constructor
only. No other method is allowed to call.
 super() must be first statement of the constructor.
 Both this(), super() methods must be call inside the
Constructor.
 But at a time only one is allowed to call either this() or
super().

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
27
27
Example
public class Parent
{
public Parent()
{
System.out.println("Parent class constructor:");
}
}
class Child extends Parent
{
public Child()
{
super();//calling parent class constructor
}
public static void main(String[] args) {
Child c=new Child();
}
}
MLR INSTITUTE OF TECHNOLOGY
18-Feb-24
28
28
class Child extends Parent
{
public Child()
{

}
public void m1()
{
super();

public static void main(String[] args) {


Child c=new Child();
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
29
29
class Child extends Parent
{
public Child()
{
this();
super();
}
public static void main(String[] args) {
Child c=new Child();
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
30
30
Polymorphism
 Poly=Many
 Morph=forms
 Polymorphism means "many forms", Performing
single task in many ways.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
31
31
Method Overloading
 It is a process of rewriting a method with different
signatures within the same class is called Method
overloading.
 Two methods are said to be overloaded methods if and
only if two methods are having same name but
different argument list.
 Method overloading can be done in one class.
 We can overload any number of methods

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
32
32
Method Overloading
 The compiler does not consider return type when
differentiating methods, so you cannot declare two
methods with the same signature even if they have
a different return type.
 Method resolution takes care by the Compiler.
 This process also called Compile time
polymorphism (or) Static binding (or) Early
binding.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
33
33
Example
public class MethodOverloading
{
public int getSum(int a,int b)
{
return a+b;
}

public float getSum(float a,float b)


{
return a+b;
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
34
34
Method Overriding
 Rewriting a parent class method in child class is
called Method overriding.
 Overriding concept is possible if and only if two
classes should be in Parent – Child relationship.
 In Method overriding JVM is the responsible for
Method resolution based on object type.
 This process also called as Dynamic binding (or)
Late binding (or) Dynamic polymorphism.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
35
35
Rules for Method Overriding
 In method overriding method name and method
signature should be same.
 Return type: Must be same(optionally covariant type )
 Modifier : Method scope should not decrease
 Scope order as follows :
public>protected>default>private
 Possible cases:
 public  public
 protected  protected, public
 default  default, protected, public
 private  (Private methods are can not be
override)

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
36
36
Abstraction

 In Object-oriented programming, abstraction is a


process of hiding the internal implementation
details from the user, only the essential functionality
will be provided to the user.
 Abstraction can be achieved with either abstract
classes or interfaces

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
37
37
Normal Methods Vs Abstract
Methods
Normal methods:
 Normal method contains declaration as well
as method definition
Ex: public void method()
{
---------
--------body;
---------
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
38
38
Normal Methods Vs Abstract
Methods
 Abstract methods:
 The method which is having declaration but not
definition such type of methods are called abstract
methods.
 Every abstract method should end with “;”.
 The child classes are responsible to provide
implementation for parent class abstract methods.
 Ex: abstract void method(); //abstract
method
 Note: The methods marked abstract end in a
semicolon rather than curly braces.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
39
39
Abstract Class
 If a class contains at least one abstract method then
it is a abstract class.
 To specify the particular class is abstract and
particular method is abstract method to the compiler
use abstract modifier.
 It is not possible to create an object to the Abstract
class. Because it contains the unimplemented
methods.
 For any class if we don’t want instantiation then we
have to declare that class as abstract i.e., for abstract
classes instantiation (creation of object) is not
possible.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
40
40
Example
abstract class Test
{
abstract public void m1();
public void m2()
{
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
41
41
Example
 Abstract method (all) implementation should be done
in Child class
 abstract class Parent
{
abstract public void m1(); // abstract method
}
class Demo extends Parent
{
public void m1()
{
System.out.println("Method m1() implementation");
}
}
MLR INSTITUTE OF TECHNOLOGY
18-Feb-24
42
42
Key Points

 Even though class does not contain any abstract


method still we can declare the class as abstract.
 Abstract class contain zero or more number of
abstract methods.
 For abstract classes it is not possible to create an
object

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
43
43
Key Points
 abstract class Test
{
void m1()
{
System.out.println("m1-method");
}
void m2()
{
System.out.println("m2-method");
}
public static void main(String[] args)
{
//Compile time Error
t.m1();
}
};

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
44
44
Interfaces
 Interface is also one type of class and It contains only
abstract methods.
 All interface methods are implicitly public and
abstract.
 For the every interface compiler will generates .class
files
 Each and every interface by default abstract hence it is
not possible to create an object.
 Interfaces not alternative for abstract class it is
extension for abstract classes.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
45
45
Interfaces

 Interface contains only abstract methods means


unimplemented methods.
 Interface also called 100% Abstract class.
 Interfaces giving the information about the
functionalities or Services And it will hide the
information about internal implementation.
 To provide implementation for abstract methods we have
to use implements Keyword
 For the interfaces also inheritance concept is applicable.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
46
46
Interfaces

 By using interface keyword we can declare interfaces in


Java
Syntax:
interface Interface_Name
{
--
}
Ex: interface Demo
{
void m1();
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
47
47
Example

interface InterfaceDemo
{
void m1(); abstract interface InterfaceDemo
void m2(); {
void m3(); public abstract void m1();
} public abstract void m2();
public abstract void m3();
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
48
48
Example

 Every variable in Interface by default public static final


interface InterfaceDemo
{
int i=10;
}

public static final int i=10;

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
49
49
Example
interface InterfaceDemo1
{
public void method1();
public void method2();
}
interface InterfaceDemo2 extends InterfaceDemo1
{
public void method3();
public void method4();
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
50
50
Example
class Demo implements InterfaceDemo2
{
@Override
public void method1() {
System.out.println("InterfaceDemo1- method1() implementation");

}
@Override
public void method2() {
System.out.println("InterfaceDemo2- method2() implementation");

}
@Override
public void method3() {
System.out.println("InterfaceDemo3- method3() implementation");
}
@Override
public void method4() {
System.out.println("InterfaceDemo4- method4() implementation");

}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
51
51
Example
interface InterfaceDemo1
{
public void method1(); Multiple inheritance
} with respect to Interfaces
interface InterfaceDemo2
{
public void method2();
public void method3();
}
class Demo implements InterfaceDemo1,InterfaceDemo2
{
@Override
public void method1() {
System.out.println("InterfaceDemo1- method1() implementation");
}
@Override
public void method2() {
System.out.println("InterfaceDemo2- method2() implementation");
}
@Override
public void method3() {
System.out.println("InterfaceDemo3- method3() implementation");
}
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
52
52
Packages
 The package contains group of related classes ,
interfaces, sub packages.
 The package is an encapsulation mechanism it is
binding the related classes and interfaces.
 We can declare a package with the help of package
keyword.
 Package is nothing but physical directory (folder)
structure and it is providing clear-cut separation
between the project modules.
 Whenever we are dividing the project into the
packages(modules) the shareability of the project will
be increased.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
53
53
Packages
Syntax:
package package_name;

Ex: package com.mlrit;

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
54
54
Packages

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
55
55
Pre-Defined Packages
 Java predefined packages contains all predefined
classes and interfaces.
 Ex:
 java.lang ,
 Java.io,
 Java.awt ,
 Java.util
 Java.net.. etc.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
56
56
Java.lang;
 The most commonly required classes and interfaces to
write a sample program is encapsulated into a separate
package is called java.lang package.
 It is a default package , No need to import this package.
 Ex: String(class)
 StringBuffer(class)
 Object(class)
 Runnable(interface)
 Cloneable(nterface)

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
57
57
Java.io;
 The classes which are used to perform the input output
operations that are present in the java.io packages.
 Ex:
 FileInputStream(class)
 FileOutputStream(class)
 FileWriter(class)
 FileReader(class)
 Serializable(Inteface)

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
58
58
Java.net;
 The classes which are required for connection
establishment in the network that classes are present
in the java.net package.
Ex:
HttpURLConnection
Socket
URL
ServerSocket
InetAddress
SocketOptions (Interface)

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
59
59
Java.util;
 Contains the collections framework, legacy collection
classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes.
 Ex:
 Calender
 Date
 Scanner
 Arrays
 ArrayList
 Collection<E> (Interface)
 Iterator<E> (Interface)
 .. etc

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
60
60
Java.sql;
 Provides the API for accessing and processing data
stored in a data source (usually a relational database)
using the JavaTM programming language.
 Ex:
 Date
 DriverManager
 Blob (Interface)

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
61
61
Java.awt;
 The classes which are used to prepare graphical user
interface those classes are present in the java.awt
package.
 Ex: Button (class)
 Checkbox(class)
 Choice (Class)
 List (class)
 ActiveEvent (Interface)

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
62
62
User Defined Packages
 The packages which are defined by the user are called
user defined packages.
 In the single source file it is possible to take the only
one package. If we are trying to take two packages at
that time compiler raise a compilation error.
 While taking package name we have to follow some
coding standards.
 The import statement must be in between the package
and class statement. And it is possible to declare any
number of import statements within the source file.
 It is possible to declare at most one public class.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
63
63
Advantages
 Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
 Java package removes naming collision or naming
conflicts.
 Packages provide reusability of code .
 Java package provides access protection.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
64
64
Final Keyword
 final is a keyword or modifier applicable to
 variables (for all instance, Static and local variables).
 methods
 classes

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
65
65
Final Variable
 If a variable is declared with final keyword, its value
can’t be modified, and we can make a variable as a
constant.
 We must initialize a final variable, otherwise compiler
will generates compile-time error.
 Ex: public static final double PI=3.141592653589793

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
66
66
Final Class
 When a class is declared with final keyword, it is called
a final class.
 If a class is declared as final, then we cannot inherit
that class i.e., we cannot create any child class for
that final class.
 Ex: You can not create child class to the String
class . Because String is the final class.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
67
67
Example
final class Demo
{
int a=10;
void m1()
{
System.out.println("m1 method is final");
System.out.println(a=a+1);
}
public static void main(String[] args)
{
Demo d=new Demo();
d.m1();
}
} MLR
18-Feb-24 INSTITUTE OF TECHNOLOGY 68
68
Final Method
 If a method is declared with final keyword, it is called a
final method. A final method cannot be overridden.
 If you want to restrict implementation of a method
then you can declare it as final.
 For example in Object class we can override some
methods like equals(), toString() but you cant override
method like wait(), notify(), notifyAll() because these
methods are declared as final.

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
69
69
Final Method
class Parent
{
public void m1()
{
System.out.println("Parent class method ... m1()");
}

public final void m2()


{
System.out.println("It is method -2");
}
}

class Child extends Parent


{
public void m1()
{
System.out.println("Hello this is child class method..m1()");
}

public void m2()


{
//Compile thime error
}

MLR INSTITUTE OF TECHNOLOGY


18-Feb-24
70
70
MLR INSTITUTE OF TECHNOLOGY
18-Feb-24
71
71

You might also like