0% found this document useful (0 votes)
21 views

Module 3

Uploaded by

Vinayak Garg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Module 3

Uploaded by

Vinayak Garg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

MODULE 3

INHERITANCE
1
FINAL
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.
1. variable
2. method
3. class

2
FINAL
•A variable can be declared as final.
•Doing so prevents its contents from being modified.
•This means that you must initialize a final variable when it is declared.
•It is a common coding convention to choose all uppercase identifiers for final variables.
•Variables declared as final do not occupy memory on a per-instance basis.
•Thus, a final variable is essentially a constant.
•A field that is both static and final has only one piece of storage that cannot be changed.
•The keyword final can also be applied to methods, and classes.
•A final variable that is not initialized at the time of declaration is known as blank final variable. We can
initialize using constructors only.
•A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.

3
FINAL
class A{ class Bike11{
int cube(final int n)
static final int data;//static blank final variable
{
static {data=50;} n=n+2; //can't be changed as n is
final
n*n*n;
public static void main(String args[]){ }
public static void main(String args[]){
System.out.println(A.data); Bike11 b=new Bike11();
} b.cube(5);
}
} }

you declare any parameter as final, you cannot change the value of it.
Can we declare a constructor final?
No, because constructor is never inherited.

4
Final Method
❑If you make any method as final, you cannot override it.
❑Is final method inherited?
Yes, final method is inherited but you cannot override it.
class Bike{
final void run(){
System.out.println("running");
}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){ Honda honda= new Honda(); honda.run();
}
}
Output: Compile Time Error

5
Final Class
If you make any class as final, you cannot extend it.

class Bike{
final void run(){
System.out.println("running");
}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
}
class finalMethod
{
public static void main(String args[]){
Honda h= new Honda(); h.run();
}
}

6
Inheritance
• Inheritance Basics

Usage of Super Creating Multi level hierarchy when constructors are executed Method
overriding dynamic method dispatch Using abstract class Final keyword, the object class.

7
INHERITANCE
✓Java inheritance refers to the ability in Java for one class to inherit from another class.
✓In Java this is also called extending a class. One class can extend another class and thereby inherit
from that class.
✓When one class inherits from another class in Java, the two classes take on certain roles. The class
that extends (inherits from another class) is the subclass and the class that is being extended (the
class being inherited from) is the superclass .
✓In other words, the subclass extends the superclass. Or, the subclass inherits from the superclass.
✓Another commonly used term for inheritance is specialization and generalization. A subclass is a
specialization of a superclass, and a superclass is a generalization of one or more subclasses.
✓Inheritance is a Method of Code Reuse.
✓extends is the keyword used to inherit the properties of a class

8
INHERITANCE -SYNTAX
class Subclass-name extends Superclass-name
{
//methods and fields
}

9
What is Inherited?
✓ When a subclass extends a superclass in Java, all protected and public fields and methods of the superclass
are inherited by the subclass.
✓By inherited is meant that these fields and methods are part of the subclass, as if the subclass had declared
them itself.
✓protected and public fields can be called and referenced just like the methods declared directly in the
subclass.
✓Fields and methods with default (package) access modifiers can be accessed by subclasses only if the
subclass is located in the same package as the superclass.
✓Private fields and methods of the superclass can never be referenced directly by subclasses. They can,
however, be referenced indirectly via methods reachable from the subclass (e.g default (package), protected
and public methods).
✓Constructors are not inherited by subclasses, but a subclass constructor must call a constructor in the
superclass.

10
Types of Inheritance
➢ Single Inheritance
➢ Multilevel Inheritance
➢ Hierarchical Inheritance
➢ Multiple Inheritance (through Interfaces)
➢ Hybrid Inheritance (through Interfaces)

11
Single Inheritance
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

12
Single Inheritance
public class MyCalculation extends Calculation{
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given
numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
MyCalculation demo = new MyCalculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

13
package examplejava; public class SimpleInheritance { output
//A simple example of inheritance. public static void main(String args[]) { Contents of superOb
//Create a superclass. A superOb = new A(); i and j: 10 20
class A { B subOb = new B();
int i, j; // The superclass may be used by itself. Contents of subOb:
void showij() { superOb.i = 10; i and j: 7 8
System.out.println("i and j: " + i + " " + j); superOb.j = 20; System.out.println("Contents of k: 9
} superOb: "); superOb.showij();
} System.out.println(); Sum of i, j and k in su
/* The subclass has access to all public members i+j+k: 24
//Create a subclass by extending class A. of its superclass. */
class B extends A { subOb.i = 7;
int k; subOb.j = 8;
void showk() { subOb.k = 9;
System.out.println("k: " + k); System.out.println("Contents of subOb: ");
} subOb.showij(); subOb.showk(); System.out.println();
void sum() { System.out.println("Sum of i, j and k in subOb:");
System.out.println("i+j+k: " + (i+j+k)); subOb.sum();
} }
} }

14
Multilevel Inheritance
Hierarchical Inheritance

15
Hierarchical Inheritance //Inherits feature of Faculty class
class CSEDept extends Faculty{
package examplejava; public void learn() {
class Faculty System.out.println("Computer Science Department ...");
{ }
public void JP() { }
System.out.println("Java programming..."); //Inherits feature of same Faculty class
} class ECEDept extends Faculty{
void CP() { public void learn() {
System.out.println("C Programming..."); System.out.println("\nECE Department...");
} }
void CPP() { }
System.out.println("C ++ Programming..."); //Inherits feature of same Faculty class
} class HSDept extends Faculty{
} public void learn() { System.out.println("\nHS Department...");
}
}

16
public class HierarchicalInheritance { OUTPUT:
public static void main(String[] args) { Computer Science Department ...
CSEDept c = new CSEDept(); Java programming...
c.learn();
c.JP(); ECE Department...
C Programming...
ECEDept e = new ECEDept();
e.learn(); HS Department...
e.CP(); C ++ Programming...

HSDept h = new HSDept();


h.learn();
h.CPP();

}
}

17
18
19
private -
Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private.
A class member that has been declared as private will remain private to its class. It is
not accessible by any code outside its class, including subclasses.
class A {
int i; // public by default private int j; // private to A void setij(int x, int y) {
i = x; j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total; void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
20
Using super
• Whenever a subclass needs to refer to its immediate
superclass, it can do so by use of the keyword super.
• super has two general forms.
– The first calls the superclass’ constructor.
– The second is used to access a member of the
superclass that has been hidden by a member of a
subclass.

21
1. Using super to Call Superclass Constructors

22
// A complete implementation of BoxWeight. // constructor used when cube is created
class Box { Box(double len) {
private double width; width = height = depth = len;
private double height; }
private double depth; // compute and return volume
// construct clone of an object double volume() {
Box(Box ob) { // pass object to constructor return width * height * depth;
width = ob.width; }
height = ob.height; }
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); BoxWeight mycube =
new BoxWeight(3, 2); BoxWeight myclone = new
BoxWeight(mybox1); double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol); OUTPUT
System.out.println("Weight of mybox1 is " + mybox1.weight);
Volume of mybox1 is 3000.0
System.out.println();
vol = mybox2.volume(); Weight of mybox1 is 34.3
System.out.println("Volume of mybox2 is " + vol); Volume of mybox2 is 24.0
System.out.println("Weight of mybox2 is " + mybox2.weight); Weight of mybox2 is 0.076
System.out.println(); Volume of mybox3 is -1.0
vol = mybox3.volume(); System.out.println("Volume of mybox3
Weight of mybox3 is -1.0
is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight); Volume of myclone is 3000.0
System.out.println(); Weight of myclone is 34.3
vol = myclone.volume(); System.out.println("Volume of myclone Volume of mycube is 27.0
is " + vol); Weight of mycube is 2.0
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
2. A Second Use for super

• The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used.
Super . member
• Here, member can be either a method or an instance variable.
• This second form of super is most applicable to situations in which member names
of a subclass hide members by the same name in the superclass.

26
package examplejava;
//Using super to overcome name hiding.
class A1 {
int i;
}
class B1 extends A1 {
int i; // this i hides the i in A
B1(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
OUTPUT:
public class UseSuper2 {
i in superclass: 1
public static void main(String[] args) {
i in subclass: 2
// TODO Auto-generated method stub
B1 subOb = new B1(1, 2); subOb.show();
}}

27
When Constructors Are Called?
• When a class hierarchy is created, in what order are the constructors
for the classes that make up the hierarchy called?
• The answer is that in a class hierarchy, constructors are called in order
of derivation, from superclass to subclass.
• Further, since super() must be the first statement executed in a
subclass’ constructor, this order is the same whether or not super( )
is used.
• If super( ) is not used, then the default or parameterless constructor
of each superclass will be executed.

28
// Create a super class. class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A { B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) { C c = new C();
}
}

29
Method Overriding
• In a class hierarchy, when a method in a subclass has the
same name and type signature as a method in its
superclass, then the method in the subclass is said to
override the method in the superclass.
• When an overridden method is called from within a
subclass, it will always refer to the version of that method
defined by the subclass.
• The version of the method defined by the
superclass will be hidden.
package examplejava;
//Method overriding. // display k – this overrides show() in A
class Ax { void show() {
int i, j; System.out.println("k: " + k);
Ax(int a, int b) { }
i = a; }
j = b; public class MethodOverride {
} public static void main(String args[]) {
//display i and j Bx subOb = new Bx(1, 2, 3);
void show() { subOb.show(); // this calls show() in B
System.out.println("i and j: " + i + }
" " + j);
}
} }
class Bx extends Ax { int k;
Bx(int a, int b, int c) {
OUTPUT:
super(a, b);
k: 3
k = c;
}
super.show(); // this calls A's show()
i and j: 1 2
k: 3

31

You might also like