Download presentation
Presentation is loading. Please wait.
1
Inheritance in Java
2
The term inheritance implies that one class can inherit a part or all of its structure and behavior from another class. Inheritance provides the idea of reusability, i.e., a code once written can be used again and again in a number of new classes. The class that does the inheriting is called a subclass of the class from which it inherits.
3
If class B is a subclass of class A, it can also be said that class A is a super class of class B.
(Sometimes the terms derived class and base class are used instead of subclass and super class)
4
A subclass can add to the structure and behavior that it inherits.
It can also replace or modify inherited behavior (though not inherited structure). The relationship between a subclass and a super class can be shown in a diagram with the subclass below, and connected to, its super class. Class B extends A { //functions and fields }
14
TYPES OF INHERITANCE Inheritance is generally of five types : single level, multilevel, multiple, hierarchical and hybrid.
15
Single-level Inheritance
In single level inheritance, there is just one base and one derived class. It is represented as follows: Diagram
16
Multilevel Inheritance
In multilevel inheritance, there is one base class and one derived class at the same time at one level. At the next level, the derived class becomes base class for the next derived class and so on. This is shown as:
18
The class A and class B together form one level, class B and class C together form another level and so on. For class B, class A is the parent and for class C, class B is the parent; thus in this inheritance level, A can be called the grandparent of class C, and class C the grandchild of class A.
19
Multiple Inheritance In a multiple inheritance, a child can have more than one parent, i.e., a child can inherit properties from more than one class. Diagrammatically, this is as shown below:
20
Not supported in Java
21
That is, in Java one cannot write the following syntax:
Unfortunately, Java does not support the multiple inheritances through classes though it supports using interfaces which is discussed in the next chapter. That is, in Java one cannot write the following syntax: class A { } class B {} class C extends A extends B
22
Hierarchical Inheritance
In this type of inheritance, multiple classes share the same base class. That is, numbers of classes inherit the properties of one common base class. The derived classes may also become base classes for other classes.
24
Examples For example, a university has a number of colleges under its affiliation. Each college may use the university name, the name of its chairperson, its address, phone number, etc.
25
Similarly, a vehicle possesses a number of properties or features and the common properties of all the vehicles may be put under one class vehicle, and different classes like two-wheeler, four-wheeler and three- wheeler can inherit the vehicle class.
26
As another example, in an engineering college, various departments can be termed as various classes which may have one parent common class-the name of the engineering college. Again for each department, there may be various classes, like lab staff, faculty class, etc.
31
Create a class Area. Having length and breadth.
Create another class Volume extends Area. In main() create object of class volume. Calculate area and volume. Enter data through keyboard.
39
METHOD OVERRIDING In method overriding, a base class method is overridden in the derived class. That is, the same method is written with the same signature as of the base class method but different implementation.
40
In method overloading, arguments and type of arguments are used to distinguish between two functions, but in method overriding no such distinction can be made. In method overriding, the signature of the two methods must match. This is shown in the program given below.
42
If you write int show() { and a return 0;} it can’t override and show error.
47
Write a program to override calculate() method.
In super class write method calculate for cube. In base class write method calculate for square. From main() calculate square and cube of a number.
50
You may write that int show(int x) in class B also.
51
DYNAMIC METHOD DISPATCH
Binding is the process of linking the function call with the place where function definition is actually written so that when a function call is made, it can be ascertained where the control has to be transferred. Binding is also called linking, and is of two types: 1. Static binding 2. Dynamic binding.
52
Static binding When at compile time, it is known which function will be called in response to a function call, the binding is said to be static binding, compile time binding or early binding. Static binding is called so because before the program executes, it is fixed that a particular function be called in response to a function call. Each time the program executes, the same function will be called. As the linking is done at compile time, early to the execution of the program, it is also known as compile time binding or early binding.
53
Dynamic Binding When it is not ascertained as to which function is to be called in response to a function call, binding is delayed till the program executes. At run time, the decision is taken as to which function is to be called in response to a function call. This type of binding is known as late binding, runtime binding or dynamic binding.
54
It is necessary in situations, where there are two functions with the same name in both derived class and base class. At run time, it is decided using references and objects, as to which function of which class is to be called.
55
‘Dynamic method dispatch’ is the mechanism by which a call to an overridden function is resolved at run time, rather than at compile time. It is the mechanism through which Java implements run time polymorphism. Before understanding this, it is important to understand the concept of Java in inheritance: “A super class reference can refer to a derived class object”. For example consider the code:
56
A super class reference can refer to a derived class object (no overriding case)
57
Make show_A() and show_B() as a same overriding function. Then obj2
Make show_A() and show_B() as a same overriding function. Then obj2.show it will print from B. But in this case(previous slide) there is no overriding. Show_A() and show_B() are different. Using base class reference you can’t access derive class method. So obj2.show_B() is not possible.
60
Using one object we can access methods of base class and derived class
66
HIERARCHICAL INHERITANCE
In this type of inheritance, one class can be a parent of many other classes. Here class A is the base class for all three classes: B, C and D. They can share all fields, methods of class A except private members.
67
Suppose that a program has to deal with motor vehicles, including cars, trucks and motorcycles. The program could use named Vehicles to represent all types of vehicles. The Vehicles class could include instance variables, such as registration number and owner, and instance method, such as transferOwnership(). These are variables and methods common to all vehicles. Three subclasses of Vehicle-Car, Truck and Motorcycle-could then be used to hold variables and methods specific to particular types of vehicles. The Car class might add an instance variable 'numberOfDoors‘, the Truck class might have 'numberOfAxels‘ and the Motorcycle class could have a Boolean variable 'hasSidecar'. The declarations of these classes in Java program would look, in outline, like the following:
68
Write a program to enter data and display.
70
THE SUPER KEYWORD Whenever the base class version of the function is called which is overridden in the derived class, the super keyword can be used. The super keyword always refers to the immediate base class. For example, consider the following code:
77
Usage of java super Keyword
super is used to refer immediate parent class instance variable. super() is used to invoke immediate parent class constructor. super is used to invoke immediate parent class method.
78
1)super is used to refer immediate parent class instance variable.
79
In the above example Vehicle and Bike both class have a common property speed.
Instance variable of current class is refered by instance by default, but we have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable.
80
2) super is used to invoke parent class constructor.
81
Note: super() is added in each class constructor automatically by compiler.
If u don’t use super keyword in previous program; the output remain same.
83
Another example of super keyword where super() is provided by the compiler implicitly.
84
3) super can be used to invoke parent class method
85
In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local. In case there is no method in subclass as parent, there is no need to use super.
86
Unit Charge Rs 5/ for commercial and Rs 2.5/ for domestic.
Create a class Commercial. It will have the method setname(),getname() and calculatebill(int unit) to calculate Electric bill of Commercial connection subscriber. Create another class Domestic which is a subclass of Commercial. It will have the method calculatebill(int unit) to calculate the electric bill of domestic connection Subscriber. From the main() use setname(String) and calculatebill(int unit) to find the total amount of Electricity Bill. Unit Charge Rs 5/ for commercial and Rs 2.5/ for domestic.
89
1.It is a keyword used to store current object reference.
this(current class) super(super class) 1.It is a keyword used to store current object reference. 1.It is a keyword used to store super class object in sub class. 2.Pre define instance variable used to hold current object reference. 2.Pre define instance variable used to hold super class object reference through sub class object. 3.Used to separate state of multiple objects of same class and also used to separate local variables and class level variables in a non-static method if both have same name. 3.Used to separate super class and subclass members if both have same name. 4.It must be used explicitly if non-static variables and local variables or parameter name is same. 4.It must be used explicitly if super class and sub class members have same names. 5.Can't be referred from static context. It can be printed, means can be called from System.out.println. For example System.out.println(this.x); 5.Can't be referred from static context. It can't be printed, means cannot be called from System.out.println. For example System.out.println(super.x); it leads to compile time error.
90
CONSTRUCTOR AND INHERITANCE
This section discusses how the constructors are called when they are present both in base and derived classes, and how the values are passed from derived class to base class. Assume a small example of single level inheritance in which class A is inherited by class B. Both the classes have their default constructors. When an object of class B is created, it calls the constructor of class B, but as class B has got A as its parent class, constructor of class A will be called first, followed by that of class B.
91
This is so because when derived class has inherited base class, obviously it will be using the data member from base class. Now without calling the constructor of base class, data members of base class will not be initialized and if derived class uses the uninitialized data members of base class, unexpected result may follow.
100
FINAL CLASS A final class is a class which is declared final by placing the keyword final before class definition. A final class has the property that it cannot be inherited. One example of final class is “System class” defined in package java.lang. When you say that an entire class is final, you state that you do not want to inherit from this class or allow anyone else to do so.
101
In other words, for some reason, the design of your class is such that there is never a need to make any changes, or for safety or security reasons, you do not want sub-classing. Note that the fields of a final class can be final depending on how you write. The same rules apply to final for fields regardless of whether the class is defined as final. However, because it prevents inheritance, all methods in a final class are implicitly final since there is no way to override them.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.