0% found this document useful (0 votes)
36 views14 pages

OOPJ Notes 2 1

This document covers the concepts of inheritance in Java, including types of inheritance, member access, and the use of the 'super' keyword. It discusses the benefits and costs of inheritance, polymorphism, method overriding, and abstract classes. Additionally, it provides examples and rules for implementing these concepts in Java programming.

Uploaded by

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

OOPJ Notes 2 1

This document covers the concepts of inheritance in Java, including types of inheritance, member access, and the use of the 'super' keyword. It discusses the benefits and costs of inheritance, polymorphism, method overriding, and abstract classes. Additionally, it provides examples and rules for implementing these concepts in Java programming.

Uploaded by

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

UNIT - II

CHAPTER -1
INHERITANCE
Contents
 Inheritance Concepts
 Member Access
 Using super
 Creating Multilevel Hierarchy
 Using final with inheritance
 Forms of inheritance, its benefits and costs
 Polymorphism – Adhoc and Pure Polymorphism
 Method Overriding
 Abstract classes
 Object Class
 References
INHERITANCE CONCEPTS
Inheritance: Inheritance is the process of inheriting properties of one class into another class.
Superclass: Class that is inherited into another class.
Subclass: Class that is inherited properties from another class. Subclass is a specialized version
of a superclass.

 There should be only one superclass for any subclass.


 Java does not support the inheritance of multiple superclasses into a single subclass.
 Hierarchy of inheritance is allowed in Java
 No class can be superclass of itself.
 A subclass can access all members of the superclass except private members.

Types of Inheritance:
1. Single Inheritance – One superclass One subclass

2. Multilevel Inheritance – subclass to a superclass is superclass to another subclass

3. Hierarchical Inheritance – Multiple subclasses to a superclass

B C D
4. Multiple Inheritance – Single subclass to multiple superclasses

A B

5. Hybrid Inheritance – combination of two or more other inheritance types

D E
Assigning subclass object to superclass variable: Subclass object can be assigned to superclass
variable.

class A{
int x;
A(){x=10;}
void print() {
System.out.println("In class A");
}
}
class B extends A{
int y;
B(){y=20;System.out.println(y);}
void print() {
System.out.println("In class B");
}
}
public class ReferSubClass{
public static void main(String[] args) {
A a=new A();
B b=new B();
A aa;
a.print();
b.print();
aa=a;
aa.print();
System.out.println(b.y);
System.out.println(aa.x);
aa=b;
aa.print();
System.out.println(aa.x);
// error as aa variable of A does not know about y
//System.out.println(aa.y);
}
}

Using super
 Whenever a subclass needs to refer to its immediate superclass, it can do so by use of
the super keyword
 Super has two general forms
o Calls the superclass constructor
o Accesses member of the superclass that has been hidden by a member of
subclass
Using super to access superclass members

class A1{
int x;
A1(){x=5;}
void print() {
System.out.println("In class A");
}
}

class B1 extends A1{


int x,y;
B1(){
x=-1;
y=-1;
}
void print() {
System.out.println("In class B");
}
void sum() {
print();
super.print();
System.out.println("sum of subclass members: "+(x+y));
System.out.println("sum of subclass member with superclass member:
"+(super.x+y));
}
}
public class SuperDemo {
public static void main(String[] args) {
B1 ob1=new B1();
ob1.sum();
}
}
Using super to call superclass constructors

class A1{
int x;
A1(){x=5;}
A1(int a){x=a;}
void print() {
System.out.println("In class A");
}
}
class B1 extends A1{
int x,y;
B1(){
x=-1;
y=-1;
}
B1(int x1,int x2,int x3){
super(x1);
x=x2;
y=x3;;
}
void sum() {
print();
super.print();
System.out.println("sum of subclass members: "+(x+y));
System.out.println("sum of subclass member with superclass member:
"+(super.x+y));
}
void print() {
System.out.println("In class B");
}
}
public class SuperDemo {
public static void main(String[] args) {
B1 ob1=new B1();
B1 ob2 = new B1(10,20,15);
ob1.sum();
ob2.sum();

}
}
Creating Multilevel Hierarchy
class Shape{
int noOfSides;
Shape(int x){ noOfSides=x; }
}
class Rectangle extends Shape{
double length,breadth, area;
Rectangle(int x, double y, double z){
super(x);
length=y;
breadth=z;
}
void areaOfRectangle() {
area=length*breadth;
System.out.println("Area of Rectangle: "+area);
}
}
class Cuboid extends Rectangle{
double width, volume;
Cuboid(int count, double l, int b, int w){
super(count,l, b);
width=w;
}
public void display() {
System.out.println("Number of sides= "+ noOfSides);
System.out.println("Length = "+length);
System.out.println("Breadth= "+breadth);
System.out.println("Width= "+width);
}
void volume() {
areaOfRectangle();
volume=length*breadth*width;
System.out.println("Volume of Cuboid: "+volume);
}
}
public class MultiLevelInheritance {
public static void main(String[] args) {// TODO Auto-generated method stub
Cuboid ob=new Cuboid(4,10,20,5);
ob.display();
ob.volume();
}
}
 In a class hierarchy, constructors are called in the order of derivation, from superclass to
subclass.
 If super() is not used, then the default or parameterless constructor of each superclass
eill be executed.

Forms of Inheritance
Main purpose of inheritance is substitutability.
1. specialization -- the subclass is a special case of the parent class (e.g. Car and
Vehicle).
2. specification -- the superclass just specifies which methods should be available but
doesn't give code. This is supported in java by interfaces and abstract methods.
3. construction -- The child class may change the behavior defined by the parent class
4. extension -- subclass adds new behavior of its own.
5. limitation -- the subclass restricts the inherited behavior. Violates substitutability.
Example: defining Queue as a subclass of Dequeue.
6. combination -- multiple inheritance. Provided in part by implementing multiple
interfaces.

Benefits of Inheritance
 Inheritance helps in code reuse. The child class may use the code defined in the parent
class without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class.
 In inheritance base class can decide to keep some data private so that it cannot be altered
by the derived class.

Costs of Inheritance
 Inheritance decreases the execution speed due to the increased time and effort it takes,
the program to jump through all the levels of overloaded classes.
 Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
 The changes made in the parent class will affect the behavior of child class too.
 The overuse of inheritance makes the program more complex.
Polymorphism
The polymorphism is the process of defining same method with different implementation.
Types of polymorphism
1. Adhoc polymorphism – compile time polymorphism (method overloading)
2. Pure polymorphism – run time polymorphism (method overriding)

Method overriding
 Method overriding is the process of re-defining a method in a child class that is already
defined in the parent class.
 The method overriding enables the child class to change the implementation of the
method which acquired from parent class according to its requirement.
 Method overriding follows late binding, as method binding happens at run time.
 The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
 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.
 To access the superclass version of an overridden function, use super.

class Shape1{
void draw() {
System.out.println("Draw shape");
}
}
class Square extends Shape1{
void draw() {
super.draw();
System.out.println("Draw Rectangle");
}
}
public class MethodOverridingDemo {
public static void main(String[] args) {
Shape1 parentOb = new Shape1();
Square childOb = new Square();
parentOb.draw();
childOb.draw(); //method of child class will be invoked
}
}
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.
 This can be accomplished by referring subclass object with superclass reference
variable. Ex: ParentClass parentOb= new ChildClass();

class Shape1{
void draw() {
System.out.println("Draw shape");
}
}
class Square extends Shape1{
void draw() {
super.draw();
System.out.println("Draw Rectangle");

}
}
public class MethodOverridingDemo {

public static void main(String[] args) {


Shape1 parentOb = new Shape1();
Square childOb = new Square();
parentOb.draw(); //method of superclass
childOb.draw(); //method of subclass
Shape1 ob;
ob=parentOb;
ob.draw(); // method of superclass
ob=childOb;
ob.draw(); //method of subclass
}
}

Using final with inheritance


In java, the final is a keyword and it is used with the following things.

 With variable (to create constant)


 With method (to avoid method overriding)
 With class (to avoid inheritance)
final with variables: When a variable defined with the final keyword, it becomes a constant,
and it does not allow us to modify the value.

final with methods: When a method defined with the final keyword, it does not allow it to
override. The final method extends to the child class, but the child class can not override or re-
define it.

final with class: When a class defined with final keyword, it cannot be extended by any other
class.

Accessibility of parent and child members:


instance instance method
variable of variable of of method overridden
parent child parent of child method
Parent parent = new
Parent() yes no yes no no
Child child = new Child() yes yes yes yes yes
Parent parent = new
Child() yes no yes no yes
Child child =
parent(Parent variable
which refers to Child
object) yes yes yes yes yes

Abstract Class
 An abstract class is a class that is declared abstract – it may or may not include abstract
method
 Abstract classes cannot be instantiated, but they can be subclassed.
 Abstract class determines the nature of the methods that the subclasses must
implement
 An abstract method is a method that is declared without an implementation

abstract class Shape{


abstract void area();
}
Rules to create abstract class:
 An abstract class must be created with abstract keyword.
 An abstract can be created without any abstract method.
 An abstract class may contain abstract and non-abstract methods.
 An abstract class may contain final methods that cannot be overridden.
 An abstract class may contain static methods, but the abstract method should not be
static.
 An abstract class may have a constructor that get executed when the child class object is
created.
 An abstract method must be overridden by the child class, otherwise, it must be defined
as an abstract class.
 An abstract class cannot be instantiated but can be referenced.
abstract class Shape2{
public static final double PI=22/7;
double dim1,dim2;
Shape2(double x){dim1=x;}
Shape2(double dim1,double x){
this.dim1=dim1;
dim2=x;
}
final void draw() { System.out.println("Draw a shape"); }
abstract double printArea();
}
class Rect extends Shape2{
Rect(double x, double y){ super(x,y); }
double printArea() { return dim1*dim2; }
}
class Triangle2 extends Shape2{
Triangle2(double x, double y){ super(x,y); }
double printArea() { return dim1*dim2 / 2; }
}
class Circle extends Shape2{
Circle(double x){ super(x); }
double printArea() { return dim1*dim1*PI; }
}
public class AbstractClassDemo {
public static void main(String[] args) {
Shape2 r=new Rect(10,20);
r.draw();
System.out.println("Area of Rectangle: "+r.printArea());
Shape2 t= new Triangle2(5,10);
t.draw();
System.out.println("Area of Triangle: "+t.printArea());
Shape2 c= new Circle(10);
c.draw();
System.out.println("Area of Circle: "+t.printArea());
System.out.println(Shape2.PI);
}
}
Object Class

Object is the class defined by Java.


All classes are subclasses of Object class.

Method Description
Object clone() Creates a new object that is same as the object being
cloned
boolean equals(Object object) Determines whether one object is equal to another
boolean Determines whether one object is equal to another
equalsIgnoreCase(Object ignoring case
object)
void finalize() Called before an unused object is recycled
Class getClass() Obtains the class of an object at runtime
int hashCode() Returns the hashcode associated with the invoking object
void notify() Resumes execution of a thread waiting on the invoking
object
void notifyAll() Resumes execution of all threads waiting on the invoking
object
void wait() Waits on another thread of execution
String toString() Returns a string that describes the object

References:
1. Herbert Schildt, Java: The Complete Reference, 10thEdition, McGraw Hill
Education (India) Pvt. Ltd.
2. Lesson: Interfaces and Inheritance (The Java™ Tutorials > Learning the Java Language)
(oracle.com)
3. https://www.javatpoint.com/
4. http://www.btechsmartclass.com/java/java-tutorials.html

You might also like