Unit-1 Topic 1.2 - Inheritance

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

ADVANCE JAVA

PROGRAMMING
Unit-1
Prepared By: Ms. Ankita Sharma
Assistant Professor
Department of Computer Science
GTBIT, GGSIPU

Prepared by Ankita Sharma (Assistant Professor of CSE)


AGENDA
Inheritance

Prepared by Ankita Sharma (Assistant Professor of CSE)


Agenda
• Inheritance
• Types of Inheritance
• Implementing Inheritance in Java
• Access Attributes
• Method Overriding
• Use of Final
• Method Overriding Vs Method Overloading
• Interface

Prepared by Ankita Sharma (Assistant Professor of CSE)


What is a Inheritance?
• Inheritance is an act through which a new class (child or derived) gets
created by acquiring the variables and methods in the parent class (base or
parent).
• It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class.
• In Java, Inheritance means creating new classes based on existing ones.
• A class that inherits from another class can reuse the methods and fields of
that class.
• In addition, we can add new fields and methods to our current class as well.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Components of Inheritance
• Two Major Components:
1. Parent class/ Super class /Base
class
2. Child class / Sub class / Derived
class.
A class that inherits the properties
is known as Child Class
whereas a class whose properties
are inherited is known as Parent
class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Components of Inheritance
• Now, to inherit a class we need to use
extends keyword.
• In the below example, class Son is the
child class and class Mom is the parent
class.
• The class Son is inheriting the
properties and methods of Mom class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Why do we need Inheritance?
• It creates a possibility to add new and to remove features.
• To reduce code length as we reuse the code.
• More comfortable to develop and maintain the project.
• Inheritance represents the IS-A relationship which is also known as a
parent-child relationship.
• For Method Overriding (so runtime polymorphism can be achieved).
• Inheritance can be achieved by using extends or implements keyword.
• Inheritance uses mostly for method overriding (also called as runtime
or dynamic polymorphism).
Prepared by Ankita Sharma (Assistant Professor of CSE)
Why do we need Inheritance?

Prepared by Ankita Sharma (Assistant Professor of CSE)


What is a Inheritance?
Syntax
Class superclass {
—————-
}
class subclass extends superclass
{
————–
—————–
}
The keyword “extends” is used while inheriting a class.
It defines that the functionality of the superclass is being extended to the subclass.
The new class created is called a sub-class while the inherited class is termed a parent class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Types of Inheritance
1. Single-level inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
Note: Java does not directly support multiple inheritance.
Note: Java only supports multiple inheritance when used with
interfaces.
Prepared by Ankita Sharma (Assistant Professor of CSE)
1. Single-level Inheritance
• As the name suggests, this type of inheritance occurs for only a single class. Only
one class is derived from the parent class. In this type of inheritance, the properties
are derived from a single parent class and not more than that. As the properties are
derived from only a single base class the reusability of a code is facilitated along
with the addition of new features.

Prepared by Ankita Sharma (Assistant Professor of CSE)


1. Single-level Inheritance

Prepared by Ankita Sharma (Assistant Professor of CSE)


2. Multi-level Inheritance
• The multi-level inheritance includes the involvement of at least two or more than
two classes.
• One class inherits the features from a parent class and the newly created sub-class
becomes the base class for another new class.
• As the name suggests, in the multi-level inheritance the involvement of multiple
base classes is there.
• In the multilevel inheritance in java, the inherited features are also from the
multiple base classes as the newly derived class from the parent class becomes the
base class for another newly derived class.
• Note: Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted
complexity when further extending the class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


2. Multi-level Inheritance

From the flow diagram in Figure, we can observe


that Class B is a derived class from Class A, and
Class C is further derived from Class B. Therefore
the concept of grandparent class comes into
existence in multi-level inheritance. However, the
members of a grandparent’s class cannot be
directly accessed in Java.
Therefore, Figure shows that Class C is inheriting
the methods and properties of both Class A and
Class B.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Prepared by Ankita Sharma (Assistant Professor of CSE)
3. Hierarchical Inheritance
1. The type of inheritance where many subclasses inherit from one single class is
known as Hierarchical Inheritance.
2. Hierarchical Inheritance a combination of more than one type of inheritance.
3. It is different from the multilevel inheritance, as the multiple classes are being
derived from one superclass. These newly derived classes inherit the features,
methods, etc, from this one superclass. This process facilitates the reusability of
a code and dynamic polymorphism (method overriding).

Prepared by Ankita Sharma (Assistant Professor of CSE)


3. Hierarchical Inheritance
1. In Figure, we can observe that the three classes Class B, Class C, and Class D
are inherited from the single Class A. All the child classes have the same parent
class in hierarchical inheritance.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Prepared by Ankita Sharma (Assistant Professor of CSE)
Prepared by Ankita Sharma (Assistant Professor of CSE)
4. Multiple Inheritance
Note: Java does not directly support multiple inheritance.
Note: Java only supports multiple inheritance when used with
interfaces.
Multiple inheritances is a type of inheritance where a subclass can
inherit features from more than one parent class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


5. Hybrid Inheritance
1. Hybrid inheritance is a combination of more than two types of inheritances
single and multiple. It can be achieved through interfaces only as multiple
inheritance is not supported by Java. It is basically the combination of simple,
multiple, hierarchical inheritances.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Prepared by Ankita Sharma (Assistant Professor of CSE)
1.//parent class
2.class Student
3.{
4.public void methodStudent()
5.{
6.System.out.println("The method of the class Student invoked.");
7.}
8.}
9.class Science extends Student
10.{
11.public void methodScience()
12.{
13.System.out.println("The method of the class Science invoked.");
14.}
15.}
16.class Commerce extends Student
17.{
18.public void methodCommerce()
19.{
20.System.out.println("The method of the class Commerce invoked.");
21.}
22.}

Prepared by Ankita Sharma (Assistant Professor of CSE)


1.class Arts extends Student
2.{
3.{ public void methodArts()

4.System.out.println("The method of the class Arts invoked.");


5.}
6.}
7.public class HierarchicalInheritanceExample
8.{
9.public static void main(String args[])
10.{
11.Science sci = new Science();
12.Commerce comm = new Commerce();
13.Arts art = new Arts();
14.//all the sub classes can access the method of super class
15.sci.methodStudent();
16.comm.methodStudent();
17.art.methodStudent();
18.}
19.}

Prepared by Ankita Sharma (Assistant Professor of CSE)


1.class Arts extends Student
2.{
3.{ public void methodArts()

4.System.out.println("The method of the class Arts invoked.");


5.}
6.}
7.public class HierarchicalInheritanceExample
8.{
9.public static void main(String args[])
10.{
11.Science sci = new Science();
12.Commerce comm = new Commerce();
13.Arts art = new Arts();
14.//all the sub classes can access the method of super class
15.sci.methodStudent();
16.comm.methodStudent();
17.art.methodStudent();
18.}
19.}

Prepared by Ankita Sharma (Assistant Professor of CSE)


What is Access Attributes in Java?
1.Just like any other fields of the subclass, the inherited fields can be used.
2.If we declare a field in the subclass, with the same name as in superclass,
then the subclass field will hide the superclass inherited filed.
3.The inherited method can be used as same as the subclass method are used.
4.We can define a new instance method in the subclass, that has the same
signature as one of the superclass method, called overriding.
5.We can define a new static method (class member) for the subclass, that has
the same signature as one of the superclass method, called hiding.
6.The subclass constructor invokes the superclass constructor either implicitly
if the superclass constructor is default or by using the keyword super.
Prepared by Ankita Sharma (Assistant Professor of CSE)
What is Access Modifier?
•.

Prepared by Ankita Sharma (Assistant Professor of CSE)


What is Access Modifier?
• Access modifiers are keywords that can be used to control the visibility of fields,
methods, and constructors in a class.
• Four Types of Access Modifiers
Private: We can access the private modifier only within the same class and not from
outside the class.
Default: We can access the default modifier only within the same package and not
from outside the package. And also, if we do not specify any access modifier it will
automatically consider it as default.

Prepared by Ankita Sharma (Assistant Professor of CSE)


What is Access Modifier?
• Protected: We can access the protected modifier within the same package
and also from outside the package with the help of the child class. If we do
not make the child class, we cannot access it from outside the package. So
inheritance is a must for accessing it from outside the package.
• Public: We can access the public modifier from anywhere. We can access
public modifiers from within the class as well as from outside the class and
also within the package and outside the package.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Private Modifier
• Methods, Variables and Constructors which might be declared private can
best be accessed within the declared class itself.
• Private get admission to modifier is the maximum restrictive access level.
• Class and interfaces cannot be private.
• Variables which can be declared private can be accessed outdoor the class, if
public methods are present in the class.
• Using the private modifier is the primary way that an object encapsulates
itself and cover information from the outside global.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Public Modifier
• A class, method, constructor, interface and many others declared public may
be accessed from another class.
• Consequently fields, methods, blocks declared internal a public class can be
accessed from any class.
• If we need to access public class from specific package, then you need to
import the public class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Protected Modifier
• The protected Java access modifier is available within package and outside
the package but through inheritance only.
• The protected access modifier may be applied at the information member,
method and constructor.
• It cannot be applied on the class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Default Modifier
• Default Java access modifiers manner we do no longer explicitly declare an
access modifier for a class, subject, method, etc.
• A variable or method declared without any access manipulate modifier is
available to some other class in the equal package.
• The default modifier is available only within package.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Method Overriding
• When a method is called using an object then the Java looks for the method definition in
the object’s class. If it cannot find in the subclass then it checks one level up in the
hierarchy of classes.
• But if the same method name appears in both the subclass and superclass with the same
signature (same number of arguments with the same type) then the method is said to be
overridden.
• In such a class when a method is classed by an object of the subclass then it is the
subclass’s method which would be called i.e. subclass method overrides superclass
method.
• Meaning Thereby; the method defined in the superclass is overridden or hidden from the
objects of subclass.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Method Overriding Example: Subclass has higher
priority.
Class First
{
int a;
void set_data(int aa)
{
a=aa;
}
void display ()
{
System.out.println(“A=“+a);
}
}

Prepared by Ankita Sharma (Assistant Professor of CSE)


class Second extends First
{
int b, c;
void set_data(int bb, int cc)
{
b=bb;
c=cc;
}
void display ()
{
System.out.println(“B=“+b);
System.out.println(“C=“+c);

}
}

Prepared by Ankita Sharma (Assistant Professor of CSE)


class Overload_Demo
{
public static void main (String args[])
{
First f = new First ();
Second s = new Second ();
f.set_data(-1);
s.set_data(100,90);
f.display();
s.display();
}
}
Output
A=-1
B = 100
C = 90

Prepared by Ankita Sharma (Assistant Professor of CSE)


Method Overriding
• Method overriding is needed as we know that the derived class is more specialized than
the base class. So, it becomes mandatory for the derived class to replace inadequate base
class methods with more suitable ones.
• In order for a derived class method to override a base class method, it must have the same
signature.
• When an object of the derived class invokes the method, it invokes the derived class’s
version of the method and not the base class’s.
• A derived class may call an overridden base class method by prefixing its name with the
super keyword and a dot (.) operator.
• Note: When a derived class overloads a base class method, both methods may be called
with a derived class object. While, when a derive class overrides a base class method,
only the derived class’s version of the method can be called with the derived class object.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final
• The final keyword is a non-access modifier used for classes, attributes and
methods, which makes them non-changeable (impossible to inherit or override).
• The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).
• The final keyword is called a "modifier".
• When a variable is declared with the final keyword, its value can’t be modified,
essentially, a constant.
• This also means that you must initialize a final variable.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final
• The following are different contexts where final is used.
• First of all, final is a non-access modifier applicable only to a variable, a method,
or a class.
• In Java, the final keyword is used to indicate that a variable, method, or class
cannot be modified or extended. Here are some of its characteristics:
• Overall, the final keyword is a useful tool for improving code quality and ensuring
that certain aspects of a program cannot be modified or extended.
• By declaring variables, methods, and classes as final, developers can write more
secure, robust, and maintainable code.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Characteristics of final keyword
• Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized. This is useful for declaring constants or other values that should not be modified.
• Final methods: When a method is declared as final, it cannot be overridden by a subclass. This is
useful for methods that are part of a class’s public API and should not be modified by subclasses.
• Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful
for classes that are intended to be used as is and should not be modified or extended.
• Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class. This ensures that the value of the variable is set and cannot be changed.
• Performance: The use of final can sometimes improve performance, as the compiler can
optimize the code more effectively when it knows that a variable or method cannot be changed.
• Security: final can help improve security by preventing malicious code from modifying sensitive
data or behavior.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final Eg1
class Main {
public static void main(String[] args) {
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final Eg1
class Main {
public static void main(String[] args) {
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final Eg1
class Main {
public static void main(String[] args) {
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}
Output: ERROR!javac /tmp/FNQZI77yNU/Main.java/tmp/FNQZI77yNU/Main.java:8:
error: cannot assign a value to final variable AGE AGE = 45; ^1 error

Prepared by Ankita Sharma (Assistant Professor of CSE)


Use of Final Eg2
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}
// try to extend the final class
class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
Prepared by Ankita Sharma (Assistant Professor of CSE)
Use of Final Eg2
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}// try to extend the final class
class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}

Prepared by Ankita Sharma (Assistant Professor of CSE)


Difference
Method Overloading Method Overriding
• The process of defining functions having • When methods of the subclass having the
the same name with different parameter same as that of superclass, overrides the
list is called as overloading method. methods of the superclass, then it is called
• It is a relationship between methods in the the overriding methods.
same class. • It is a relationship between subclass
• It is static binding – at the compile time. method and a superclass method.
• It is concept of compile time • It is a dynamic binding – at compile time.
polymorphism or early binding. • It is the concept of run time
• It may or may not be observed during polymorphism or a late binding.
inheritance. • Return types, methods names and
• Return types do not affect overloading. signatures, of both overridden methods
must be identical.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Difference
Method Overloading Method Overriding
• Method overloading is performed within • Method overriding occurs in two classes
class. that have IS-A relationship.
• In case of method overloading, parameter • In case of method overriding, parameter
must be different. must be same.
• Method overloading is the example of • Method overriding is the example of run
compile time polymorphism. time polymorphism.
• In java, method overloading can't be • Return type must be same or covariant in
performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But we
must have to change the parameter.

Prepared by Ankita Sharma (Assistant Professor of CSE)


What is an interface?
• Objects define their interaction with the outside world through the methods
that they expose.
• Methods form the object's interface with the outside world.
• the buttons on the front of our television set, for example, are the interface
between you and the electrical wiring on the other side of its plastic casing.
• We press the "power" button to turn the television on and off.
• In its most common form, an interface is a group of related methods with
empty bodies.
• Java Interface also represents the IS-A relationship.

Prepared by Ankita Sharma (Assistant Professor of CSE)


What is an interface?
• Implementing an interface allows a class to become more formal about the
behavior it promises to provide.
• Interfaces form a contract between the class and the outside world, and this
contract is enforced at build time by the compiler.
• In other words, we can say that interfaces can have abstract methods and
variables. It cannot have a method body.
• It cannot be instantiated just like the abstract class.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Why use Java interface?
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
• To achieve security - hide certain details and only show the important
details of an object (interface).
• Java does not support "multiple inheritance" (a class can only inherit from
one superclass). However, it can be achieved with interfaces, because the
class can implement multiple interfaces.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Relationship between classes and interfaces

Prepared by Ankita Sharma (Assistant Professor of CSE)


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.

Prepared by Ankita Sharma (Assistant Professor of CSE)


Java Interface Example

Prepared by Ankita Sharma (Assistant Professor of CSE)


Java Interface Example

Prepared by Ankita Sharma (Assistant Professor of CSE)


Multiple Interfaces

Prepared by Ankita Sharma (Assistant Professor of CSE)


Important points on Interface
• Like abstract classes, interfaces cannot be used to create objects.
• Interface methods do not have a body - the body is provided by the
"implement" class
• On implementation of an interface, you must override all of its methods
• Interface methods are by default abstract and public
• Interface attributes are by default public, static and final
• An interface cannot contain a constructor (as it cannot be used to create
objects).

Prepared by Ankita Sharma (Assistant Professor of CSE)


THANK YOU

Prepared by Ankita Sharma (Assistant Professor of CSE)

You might also like