Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views33 pages

Java Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows for the creation of hierarchical classifications through superclasses and subclasses. It enables subclasses to inherit properties and methods from superclasses while adding their own unique features. The document also discusses access specifiers, method overriding, dynamic method dispatch, and the concept of abstract classes in Java.

Uploaded by

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

Java Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows for the creation of hierarchical classifications through superclasses and subclasses. It enables subclasses to inherit properties and methods from superclasses while adding their own unique features. The document also discusses access specifiers, method overriding, dynamic method dispatch, and the concept of abstract classes in Java.

Uploaded by

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

Inheritance

Inheritance is one of the cornerstones of object-oriented programming because it allows


the creation of hierarchical classifications. Using inheritance, we can create a general
class that defines traits common to a set of related items. This class can then be inherited
by other, more specific classes, each adding those things that are unique to it. In the
terminology of Java, a class that is inherited is called a superclass. The class that does
the inheriting is called a subclass. Therefore, 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.
Inheritance
Inheritance

To inherit a class, we simply 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);
}
}
Inheritance
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
Inheritance
// 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
public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
Inheritance

subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Inheritance

Output:

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
// This program uses inheritance toInheritance
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;
}
Inheritance
// constructor
Box() {
width = -1;
height = -1;
depth = -1;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Inheritance

// Here, Box is extended 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;
}
}
Inheritance
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
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);
}
}
Inheritance

Output:

Volume of mybox1 is 3000.0


Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
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.
// 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;
}
}
Using 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.
// 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
}
Using super
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}

class UseSuper {
public static void main(String args[])
{ Output:
B subOb = new B(1, 2); i in superclass: 1
subOb.show(); i in subclass: 2
}
}
Access Specifier
There are four types of access specifiers/modifiers in java:

1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package. Child class can access the
protected members of parent class.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
Multi level inheritance
class A
{
public int x;
void printx() { System.out.println(" x=" + x); }
}
class B extends A
{
int y;
void printxy() { System.out.println("x=" + x + "," +", y=" + y); }
}
class C extends B
{
int z;
void printxyz() { System.out.println("x=" + x + "," + ", y=" + y + ", z=" + z); }
}
Multi level inheritance
class multi
{
public static void main(String args[])
{
C ob = new C();
ob.x = 3;
ob.y = 5;
ob.z = 6;
ob.printxyz();

A ob1 = new A();


ob1.x = 8;
ob1.printx();
}
}
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.
Method Overriding

// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
Method Overriding

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);
}
}
Method Overriding

class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

Output:
K: 3
Method Overriding
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);
}
}
Output:
i and j: 1 2
k: 3
Dynamic Method Dispatch

Both the method overloading and method overriding concepts are compile time
polymorphsim and they have not much difference. But, method overriding forms
the basis for one of Java’s most powerful concepts: dynamic method dispatch.
Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.

When an overridden method is called through a superclass 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. Thus, this determination is
made at run time.
Dynamic Method Dispatch
// Dynamic Method Dispatch
class A
{
int x;
void show() { System.out.println("In class A: x = " + x); }
}

class B extends A
{
int y;
// override show()
void show() { System.out.println("In class B: x = " + x + " y = " + y); }
}
Dynamic Method Dispatch
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
a.x = 5;
b.x = 6;
b.y = 10;
Output:
A r; // obtain a reference of type A
r = a; // r refers to an A object In class A: x = 5
r.show(); // calls A's version of show() In class B: x = 6 y = 10
r = b; // r refers to a B object
r.show(); // calls B's version of show()
}
}
Diamond Problem in multiple inheritance
Multiple Inheritance is a feature of object oriented concept, where a class can
inherit properties of more than one parent class. The problem occurs when there
exist methods with same signature in both the super classes and subclass. On
calling the method, the compiler cannot determine which class method to be
called and even on calling which class method gets the priority.
A
void fun()

B C
void fun() void fun()

D
Which void fun() ?
Diamond Problem in multiple inheritance
class Parent1
{
void fun()
{
System.out.println("Parent1");
}
}

// Second Parent Class


class Parent2
{
void fun()
{
System.out.println("Parent2");
}
}
Diamond Problem in multiple inheritance
// Error : Test is inheriting from multiple classes

class Test extends Parent1, Parent2 //this code is not allowed in java
{
public static void main(String args[]) Output:
{ Compile error
Test t = new Test();
t.fun();
}
}
From the code, we see that, on calling the method fun() using Test object will
cause complications such as whether to call Parent1’s fun() or Parent2’s fun()
method.
Abstract Class

There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of
every method. That is, sometimes you will want to create a superclass that only
defines a generalized form that will be shared by all of its subclasses, leaving it to
each subclass to fill in the details.

abstract type name(parameter-list);


Abstract Class


1. Any class that contains one or more abstract methods must also be declared
Abstract.
2. It can have abstract and non-abstract methods.
3. It can have constructors and static methods.
4. Abstract class must be declared with an abstract keyword.
5. It can have final methods.
6. An abstract class cannot be directly instantiated with the new operator.

7. Any subclass of an abstract class must either implement all of the abstract
methods of the superclass, or be itself declared abstract.
abstract class Person
Abstract Class
{
public abstract String getDescription();
}

abstract class Person


{
public Person(String n)
{
name = n;
}
public abstract String getDescription();
public String getName()
{
return name;
}
private String name;
}
Abstract Class

class Student extends Person


{
public Student(String n, String m)
{
super(n);
major = m;
}
public String getDescription()
{
return "a student majoring in " + major;
}
private String major;
}

You might also like