SlideShare a Scribd company logo
1 of 55
INHERITANCE
1
2
Inheritance
• Allows the creation of hierarchical
classifications
• In the terminology of Java, a class that is
inherited is called a superclass
• The class that does the inheriting is called a
subclass
3
• A subclass is a specialized version of a
superclass
• It inherits all of the instance variables and
methods defined by the superclass and adds
its own, unique elements
• Incorporate the definition of one class into
another by using the extends keyword
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
} // Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
4
5
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A(); B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10; superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij(); System.out.println();
/* The subclass has access to all default and public
members of its superclass. */
subOb.i = 7; subOb.j = 8; subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
} }
6
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
7
• A subclass can be a superclass for another
subclass
• The general form of a class declaration that
inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
• Java does not support the inheritance of
multiple superclasses into a single subclass
8
Member Access and Inheritance
• Subclass 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 its subclass.
9
// Create a superclass.
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
}
}
10
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
// This program uses inheritance to extend Box.
class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
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; } 11
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box }
// constructor used when cube is created
Box(double len) {
width = height = depth = len; }
// compute and return volume
double volume() {
return width * height * depth; }
}
12
// Here, Box is extened to include weight.
class BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
} }
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
13
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
14
• A superclass variable can reference a subclass
object derived from that superclass:
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " +
weightbox.weight);
System.out.println();
15
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " +
plainbox.weight);
}
}
16
17
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
• A subclass can call a constructor method defined by
its superclass by use of the following form of super:
super(parameter-list);
18
• parameter-list specifies any parameters needed by the
constructor in the superclass
// BoxWeight now uses super to initialize its Box
attributes.
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
• This leaves Box free to make these values private if
desired
19
A Second Use for super
• It always refers to the superclass of the subclass in
which it is used
• This usage has the following general form:
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
20
// Using super to overcome name hiding.
class A {
int i; }
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(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);
} }
21
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2
22
Creating a Multilevel Hierarchy
• Given three classes called A, B, and C, C can be
a subclass of B, which is a subclass of A
• C inherits all aspects of B and A
• super always points to the constructor in the
closest super class.
23
class Box {
private double width;
private double height;
private double depth;
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
24
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
} }
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
BoxWeight() {
super();
weight = -1; }
BoxWeight(double len, double m) {
super(len);
weight = m;
} }
class Shipment extends BoxWeight {
double cost;
Shipment(Shipment ob) { // pass object to constructor
super(ob);
cost = ob.cost;
}
25
26
Shipment(double w, double h, double d,double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}
Shipment() {
super();
cost = -1;
}
Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 =new Shipment(10, 20, 15, 10, 3.41);
27
Shipment shipment2 =new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "+
shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "+
shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
• Output of the program :
volume of shipment 1 is 3000.0
weight of shipment 1 is 10.0
Shipping cost : $3.41
volume of shipment 2 is 24
weight of shipment 2 is 0.76
Shipping cost : $1.28
28
29
When Constructors Are Called ?
• In a class hierarchy, constructors are called in order of
derivation, from superclass to subclass
• 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 parameter-less
constructor of each superclass will be executed
30
// 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.");
}
}
31
class CallingCons {
public static void main(String args[])
{
` C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
32
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
33
• 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
34
class A {
int i, j;
A(int a, int b) {
i = a;
j = b; }
void show() {
System.out.println("i and j: " + i + " " + j);
} }
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c; }
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
35
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
• If you wish to access the superclass version of an
overridden function, you can do so by using super
36
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
37
• Method overriding occurs only when the
names and the type signatures of the two
methods are identical
• If they are not, then the two methods are
simply overloaded
38
// Methods with differing type signatures are overloaded – not
overridden.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b; }
void show() {
System.out.println("i and j: " + i + " " + j);
} } // Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c; } // overload show()
void show(String msg) {
System.out.println(msg + k);
} }
39
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}
The output produced by this program is shown here:
This is k: 3
i and j: 1 2
Dynamic method dispatch:
• This is the mechanism by which a call to an overridden
method is resolved at run-time, rather than compile-
time. Through this , java implements run-time
polymorphism.
• When an overridden method is called through a super
class reference, java determines which version of that
method to execute based upon the type of the object
being referred to at the time the call occurs. This is
made at run-time.
• It is the type of the object being referred to (not the
type of the reference variable) that determines the
version to be executed.
40
class A {
void callme() {
System.out.println("Inside A's callme method");
} }
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
} }
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
} 41
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
} 42
Why overridden methods?
• Polymorphism allows a general class to specify
methods that will be common to all of its derivatives,
while allowing subclasses to define the specific
implementation of some or all of those methods.
• Overridden methods allow java to support run-time
polymorphism or “one interface, multiple methods”
aspect of polymorphism.
• By combining inheritance with overridden methods, a
super class can define the general form of the methods
that will be used by all of its subclasses.
• This gives java – code reuse and robustness.
43
// Applying method overriding (Using run-time polymorphism)
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
} }
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b); } 44
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2; }
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b); }
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
45
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
} 46
Using abstract classes:
• It may be needed to define a superclass that declares
the structure of a given abstraction without giving a
complete implementation of every method. Such a
class determines the nature of the methods that the
subclass must implement.
• This is - when a superclass is unable to create a
meaningful implementation for a method.
• To ensure that a subclass overrides all necessary
methods – java provides “abstract method”
• general form: abstract type name(param-list);
• Any class that contain one or more abstract methods
also be declared abstract.
47
• To declare a class abstract, use the abstract keyword
in front of the class keyword. There can be no
objects of an abstract class.
• You can not declare abstract constructors or abstract
static methods.
• Any subclass of an abstract class must either
implement all of the abstract methods or be itself
declared abstract.
• Abstract classes can be used to create object
references to implement run-time polymorphism.
This reference can be used to point to subclass
object. 48
abstract class A { // A Simple demonstration of abstract.
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method."); } }
class B extends A {
void callme() {
System.out.println("B's implementation of callme."); }
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B(); b.callme();
b.callmetoo(); }
} 49
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
} // area is now an an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
50
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
} }
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
} } 51
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
} 52
Using final with inheritance:
• To prevent overriding: to disallow a method from being
overridden, specify final as a modifier.
• When a small final method is called, java compiler can copy
the byte code for the subroutine directly inline with the
compiled code of the calling method.
• Inlining is only an option with final methods( early binding).
class A {
final void meth() {
System.out.println("This is a final method."); } }
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!"); } } 53
• To prevent inheritance: precede the class
declaration with final. It implicitly declares all of its
methods as final.
• It is illegal to declare a class as both final and
abstract since an abstract class is incomplete by
itself and relies upon its subclasses to provide
complete implementations.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
} 54
• The following pattern be followed while setting the question paper for in-
semester examination for IV semester B Tech students:
•
• 2 MARKS : FOUR (2 x 4 = 8)
• 3 MARKS : THREE (3 X 3 = 9)
• 4 MARKS : TWO (4 X 2 = 8)
• 5 MARKS : ONE (5 X 1 = 5)
• -----------------------------------
• TOTAL: 30 MARKS
• -----------------------------------

More Related Content

Similar to 6.INHERITANCE.ppt(MB).ppt .

Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oopAHHAAH
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritanceNurhanna Aziz
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfkakarthik685
 
5.CLASSES.ppt(MB)2022.ppt .
5.CLASSES.ppt(MB)2022.ppt                       .5.CLASSES.ppt(MB)2022.ppt                       .
5.CLASSES.ppt(MB)2022.ppt .happycocoman
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxRDeepa9
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Unit3 java
Unit3 javaUnit3 java
Unit3 javamrecedu
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Multi level hierarchy
Multi level hierarchyMulti level hierarchy
Multi level hierarchymyrajendra
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Shweta Shah
 

Similar to 6.INHERITANCE.ppt(MB).ppt . (20)

Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oop
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritance
 
Chapter ii(oop)
Chapter ii(oop)Chapter ii(oop)
Chapter ii(oop)
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
 
5.CLASSES.ppt(MB)2022.ppt .
5.CLASSES.ppt(MB)2022.ppt                       .5.CLASSES.ppt(MB)2022.ppt                       .
5.CLASSES.ppt(MB)2022.ppt .
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
 
Inheritance
Inheritance Inheritance
Inheritance
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
class object.pptx
class object.pptxclass object.pptx
class object.pptx
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
10. inheritance
10. inheritance10. inheritance
10. inheritance
 
Multi level hierarchy
Multi level hierarchyMulti level hierarchy
Multi level hierarchy
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 

More from happycocoman

gas turbine cycles.pptx .
gas turbine cycles.pptx                    .gas turbine cycles.pptx                    .
gas turbine cycles.pptx .happycocoman
 
RECIPROCATING_AIR_COMPRESSOR.ppt .
RECIPROCATING_AIR_COMPRESSOR.ppt         .RECIPROCATING_AIR_COMPRESSOR.ppt         .
RECIPROCATING_AIR_COMPRESSOR.ppt .happycocoman
 
SURFACE TEXTURE 2022.pptx .
SURFACE TEXTURE 2022.pptx                  .SURFACE TEXTURE 2022.pptx                  .
SURFACE TEXTURE 2022.pptx .happycocoman
 
Numericals on Raciprocating air compressor.ppt
Numericals on  Raciprocating air compressor.pptNumericals on  Raciprocating air compressor.ppt
Numericals on Raciprocating air compressor.ppthappycocoman
 
Vapor_power cycles KM.pptx ..
Vapor_power cycles KM.pptx            ..Vapor_power cycles KM.pptx            ..
Vapor_power cycles KM.pptx ..happycocoman
 
Vapor power cycles by Anupama.pptx .
Vapor power cycles by Anupama.pptx     .Vapor power cycles by Anupama.pptx     .
Vapor power cycles by Anupama.pptx .happycocoman
 
Performance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.pptPerformance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.ppthappycocoman
 
ICenginesNumericals (1).pptx .
ICenginesNumericals (1).pptx             .ICenginesNumericals (1).pptx             .
ICenginesNumericals (1).pptx .happycocoman
 
Air standard cycles_PPT KM1.pptx .
Air standard cycles_PPT KM1.pptx          .Air standard cycles_PPT KM1.pptx          .
Air standard cycles_PPT KM1.pptx .happycocoman
 
Pressure Measurement ppt.pptx .
Pressure Measurement ppt.pptx               .Pressure Measurement ppt.pptx               .
Pressure Measurement ppt.pptx .happycocoman
 
Measurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptxMeasurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptxhappycocoman
 
Strain Measurement (NEW).pptx .
Strain Measurement (NEW).pptx               .Strain Measurement (NEW).pptx               .
Strain Measurement (NEW).pptx .happycocoman
 
Force and torque measurements.pptx .
Force and torque measurements.pptx      .Force and torque measurements.pptx      .
Force and torque measurements.pptx .happycocoman
 
Chapter 11 - SCREW THREADS sllides.pdf .
Chapter 11 - SCREW THREADS sllides.pdf       .Chapter 11 - SCREW THREADS sllides.pdf       .
Chapter 11 - SCREW THREADS sllides.pdf .happycocoman
 
Measurement of form errors.pptx .
Measurement of form errors.pptx            .Measurement of form errors.pptx            .
Measurement of form errors.pptx .happycocoman
 
9. Surface Texture - PPT.pdf .
9. Surface Texture - PPT.pdf               .9. Surface Texture - PPT.pdf               .
9. Surface Texture - PPT.pdf .happycocoman
 
10. Screw Threads - PPT.pdf .
10. Screw Threads - PPT.pdf                    .10. Screw Threads - PPT.pdf                    .
10. Screw Threads - PPT.pdf .happycocoman
 
Measurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdfMeasurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdfhappycocoman
 
Limits Fits and Tolerances ppt.pdf .
Limits Fits and Tolerances ppt.pdf     .Limits Fits and Tolerances ppt.pdf     .
Limits Fits and Tolerances ppt.pdf .happycocoman
 

More from happycocoman (20)

gas turbine cycles.pptx .
gas turbine cycles.pptx                    .gas turbine cycles.pptx                    .
gas turbine cycles.pptx .
 
RECIPROCATING_AIR_COMPRESSOR.ppt .
RECIPROCATING_AIR_COMPRESSOR.ppt         .RECIPROCATING_AIR_COMPRESSOR.ppt         .
RECIPROCATING_AIR_COMPRESSOR.ppt .
 
SURFACE TEXTURE 2022.pptx .
SURFACE TEXTURE 2022.pptx                  .SURFACE TEXTURE 2022.pptx                  .
SURFACE TEXTURE 2022.pptx .
 
Numericals on Raciprocating air compressor.ppt
Numericals on  Raciprocating air compressor.pptNumericals on  Raciprocating air compressor.ppt
Numericals on Raciprocating air compressor.ppt
 
Vapor_power cycles KM.pptx ..
Vapor_power cycles KM.pptx            ..Vapor_power cycles KM.pptx            ..
Vapor_power cycles KM.pptx ..
 
Vapor power cycles by Anupama.pptx .
Vapor power cycles by Anupama.pptx     .Vapor power cycles by Anupama.pptx     .
Vapor power cycles by Anupama.pptx .
 
Performance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.pptPerformance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.ppt
 
ICenginesNumericals (1).pptx .
ICenginesNumericals (1).pptx             .ICenginesNumericals (1).pptx             .
ICenginesNumericals (1).pptx .
 
Air standard cycles_PPT KM1.pptx .
Air standard cycles_PPT KM1.pptx          .Air standard cycles_PPT KM1.pptx          .
Air standard cycles_PPT KM1.pptx .
 
Pressure Measurement ppt.pptx .
Pressure Measurement ppt.pptx               .Pressure Measurement ppt.pptx               .
Pressure Measurement ppt.pptx .
 
Measurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptxMeasurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptx
 
Strain Measurement (NEW).pptx .
Strain Measurement (NEW).pptx               .Strain Measurement (NEW).pptx               .
Strain Measurement (NEW).pptx .
 
Force and torque measurements.pptx .
Force and torque measurements.pptx      .Force and torque measurements.pptx      .
Force and torque measurements.pptx .
 
FLOW(NEW).pptx .
FLOW(NEW).pptx                          .FLOW(NEW).pptx                          .
FLOW(NEW).pptx .
 
Chapter 11 - SCREW THREADS sllides.pdf .
Chapter 11 - SCREW THREADS sllides.pdf       .Chapter 11 - SCREW THREADS sllides.pdf       .
Chapter 11 - SCREW THREADS sllides.pdf .
 
Measurement of form errors.pptx .
Measurement of form errors.pptx            .Measurement of form errors.pptx            .
Measurement of form errors.pptx .
 
9. Surface Texture - PPT.pdf .
9. Surface Texture - PPT.pdf               .9. Surface Texture - PPT.pdf               .
9. Surface Texture - PPT.pdf .
 
10. Screw Threads - PPT.pdf .
10. Screw Threads - PPT.pdf                    .10. Screw Threads - PPT.pdf                    .
10. Screw Threads - PPT.pdf .
 
Measurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdfMeasurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdf
 
Limits Fits and Tolerances ppt.pdf .
Limits Fits and Tolerances ppt.pdf     .Limits Fits and Tolerances ppt.pdf     .
Limits Fits and Tolerances ppt.pdf .
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 

Recently uploaded (20)

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 

6.INHERITANCE.ppt(MB).ppt .

  • 2. 2 Inheritance • Allows the creation of hierarchical classifications • In the terminology of Java, a class that is inherited is called a superclass • The class that does the inheriting is called a subclass
  • 3. 3 • A subclass is a specialized version of a superclass • It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements • Incorporate the definition of one class into another by using the extends keyword
  • 4. // Create a superclass. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } 4
  • 5. 5 class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all default and public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }
  • 6. 6 The output from this program is shown here: Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24
  • 7. 7 • A subclass can be a superclass for another subclass • The general form of a class declaration that inherits a superclass is shown here: class subclass-name extends superclass-name { // body of class } • Java does not support the inheritance of multiple superclasses into a single subclass
  • 8. 8 Member Access and Inheritance • Subclass 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 its subclass.
  • 9. 9 // Create a superclass. 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 } }
  • 10. 10 class Access { public static void main(String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.println("Total is " + subOb.total); } }
  • 11. // This program uses inheritance to extend Box. class Box { double width; double height; double depth; // construct clone of an object Box(Box ob) { // pass object to constructor 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; } 11
  • 12. // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } 12
  • 13. // Here, Box is extened to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); 13
  • 14. BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } } 14
  • 15. • A superclass variable can reference a subclass object derived from that superclass: class RefDemo { public static void main(String args[]) { BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37); Box plainbox = new Box(); double vol; vol = weightbox.volume(); System.out.println("Volume of weightbox is " + vol); System.out.println("Weight of weightbox is " + weightbox.weight); System.out.println(); 15
  • 16. // assign BoxWeight reference to Box reference plainbox = weightbox; vol = plainbox.volume(); // OK, volume() defined in Box System.out.println("Volume of plainbox is " + vol); /* The following statement is invalid because plainbox does not define a weight member. */ // System.out.println("Weight of plainbox is " + plainbox.weight); } } 16
  • 17. 17 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 • A subclass can call a constructor method defined by its superclass by use of the following form of super: super(parameter-list);
  • 18. 18 • parameter-list specifies any parameters needed by the constructor in the superclass // BoxWeight now uses super to initialize its Box attributes. class BoxWeight extends Box { double weight; // weight of box // initialize width, height, and depth using super() BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } } • This leaves Box free to make these values private if desired
  • 19. 19 A Second Use for super • It always refers to the superclass of the subclass in which it is used • This usage has the following general form: 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
  • 20. 20 // Using super to overcome name hiding. class A { int i; } // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(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); } }
  • 21. 21 class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } This program displays the following: i in superclass: 1 i in subclass: 2
  • 22. 22 Creating a Multilevel Hierarchy • Given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A • C inherits all aspects of B and A • super always points to the constructor in the closest super class.
  • 23. 23 class Box { private double width; private double height; private double depth; Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } Box(double w, double h, double d) { width = w; height = h; depth = d; }
  • 24. 24 Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } } class BoxWeight extends Box { double weight; // weight of box BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; }
  • 25. BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } BoxWeight() { super(); weight = -1; } BoxWeight(double len, double m) { super(len); weight = m; } } class Shipment extends BoxWeight { double cost; Shipment(Shipment ob) { // pass object to constructor super(ob); cost = ob.cost; } 25
  • 26. 26 Shipment(double w, double h, double d,double m, double c) { super(w, h, d, m); // call superclass constructor cost = c; } Shipment() { super(); cost = -1; } Shipment(double len, double m, double c) { super(len, m); cost = c; } } class DemoShipment { public static void main(String args[]) { Shipment shipment1 =new Shipment(10, 20, 15, 10, 3.41);
  • 27. 27 Shipment shipment2 =new Shipment(2, 3, 4, 0.76, 1.28); double vol; vol = shipment1.volume(); System.out.println("Volume of shipment1 is " + vol); System.out.println("Weight of shipment1 is "+ shipment1.weight); System.out.println("Shipping cost: $" + shipment1.cost); System.out.println(); vol = shipment2.volume(); System.out.println("Volume of shipment2 is " + vol); System.out.println("Weight of shipment2 is "+ shipment2.weight); System.out.println("Shipping cost: $" + shipment2.cost); } }
  • 28. • Output of the program : volume of shipment 1 is 3000.0 weight of shipment 1 is 10.0 Shipping cost : $3.41 volume of shipment 2 is 24 weight of shipment 2 is 0.76 Shipping cost : $1.28 28
  • 29. 29 When Constructors Are Called ? • In a class hierarchy, constructors are called in order of derivation, from superclass to subclass • 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 parameter-less constructor of each superclass will be executed
  • 30. 30 // 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."); } }
  • 31. 31 class CallingCons { public static void main(String args[]) { ` C c = new C(); } } The output from this program is shown here: Inside A’s constructor Inside B’s constructor Inside C’s constructor
  • 32. 32 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
  • 33. 33 • 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
  • 34. 34 class A { int i, j; A(int a, int b) { i = a; j = b; } void show() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // display k – this overrides show() in A void show() { System.out.println("k: " + k); } }
  • 35. 35 class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } } The output produced by this program is shown here: k: 3 • If you wish to access the superclass version of an overridden function, you can do so by using super
  • 36. 36 class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show() System.out.println("k: " + k); } }
  • 37. 37 • Method overriding occurs only when the names and the type signatures of the two methods are identical • If they are not, then the two methods are simply overloaded
  • 38. 38 // Methods with differing type signatures are overloaded – not overridden. class A { int i, j; A(int a, int b) { i = a; j = b; } void show() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // overload show() void show(String msg) { System.out.println(msg + k); } }
  • 39. 39 class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show("This is k: "); // this calls show() in B subOb.show(); // this calls show() in A } } The output produced by this program is shown here: This is k: 3 i and j: 1 2
  • 40. Dynamic method dispatch: • This is the mechanism by which a call to an overridden method is resolved at run-time, rather than compile- time. Through this , java implements run-time polymorphism. • When an overridden method is called through a super class reference, java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. This is made at run-time. • It is the type of the object being referred to (not the type of the reference variable) that determines the version to be executed. 40
  • 41. class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); } } 41
  • 42. class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } } 42
  • 43. Why overridden methods? • Polymorphism allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods. • Overridden methods allow java to support run-time polymorphism or “one interface, multiple methods” aspect of polymorphism. • By combining inheritance with overridden methods, a super class can define the general form of the methods that will be used by all of its subclasses. • This gives java – code reuse and robustness. 43
  • 44. // Applying method overriding (Using run-time polymorphism) class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Area for Figure is undefined."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } 44
  • 45. // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } 45
  • 46. class FindAreas { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } } 46
  • 47. Using abstract classes: • It may be needed to define a superclass that declares the structure of a given abstraction without giving a complete implementation of every method. Such a class determines the nature of the methods that the subclass must implement. • This is - when a superclass is unable to create a meaningful implementation for a method. • To ensure that a subclass overrides all necessary methods – java provides “abstract method” • general form: abstract type name(param-list); • Any class that contain one or more abstract methods also be declared abstract. 47
  • 48. • To declare a class abstract, use the abstract keyword in front of the class keyword. There can be no objects of an abstract class. • You can not declare abstract constructors or abstract static methods. • Any subclass of an abstract class must either implement all of the abstract methods or be itself declared abstract. • Abstract classes can be used to create object references to implement run-time polymorphism. This reference can be used to point to subclass object. 48
  • 49. abstract class A { // A Simple demonstration of abstract. abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { B b = new B(); b.callme(); b.callmetoo(); } } 49
  • 50. // Using abstract methods and classes. abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } // area is now an an abstract method abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } 50
  • 51. // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } 51
  • 52. class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); } } 52
  • 53. Using final with inheritance: • To prevent overriding: to disallow a method from being overridden, specify final as a modifier. • When a small final method is called, java compiler can copy the byte code for the subroutine directly inline with the compiled code of the calling method. • Inlining is only an option with final methods( early binding). class A { final void meth() { System.out.println("This is a final method."); } } class B extends A { void meth() { // ERROR! Can't override. System.out.println("Illegal!"); } } 53
  • 54. • To prevent inheritance: precede the class declaration with final. It implicitly declares all of its methods as final. • It is illegal to declare a class as both final and abstract since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. final class A { // ... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A // ... } 54
  • 55. • The following pattern be followed while setting the question paper for in- semester examination for IV semester B Tech students: • • 2 MARKS : FOUR (2 x 4 = 8) • 3 MARKS : THREE (3 X 3 = 9) • 4 MARKS : TWO (4 X 2 = 8) • 5 MARKS : ONE (5 X 1 = 5) • ----------------------------------- • TOTAL: 30 MARKS • -----------------------------------

Editor's Notes

  1. Constructor in multi-level hierarchy. Super keyword in all possible ways
  2. In Java programming language, the method signature consists of two parts: the method's name and the parameter list. These two parts are part of a method declaration. The parameter list includes the number, type, and order of parameters but not the name of the parameter