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

Unit 4 Part 1 Inheritance

Uploaded by

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

Unit 4 Part 1 Inheritance

Uploaded by

anaghasalunke44
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

SNJB’s Late Sau. K. B. J.

College of Engineering

SE Computer- Division A
Course Name :Principle of Programming Language
Course Code: 210256
Course InCharge: Kainjan M. Sanghavi

Thanks to Khyati R. Nirmal ..to prepare the slides

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Unit 4
Inheritance, Packages and Exception Handling using Java

Inheritances: member access and inheritance, super class references, Using super,
multilevel hierarchy, constructor call sequence, method overriding, dynamic method
dispatch, abstract classes, Object class.

Packages and Interfaces: defining a package, finding packages and CLASSPATH, access
protection, importing packages,

interfaces (defining, implementation, nesting, applying), variables in interfaces,


extending interfaces, instance of operator.

fundamental, exception types, uncaught exceptions, try, catch, throw, throws, finally,
multiple catch clauses, nested try statements, built-in exceptions, custom exceptions
(creating your own exception sub classes).
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Unit 4
Inheritance, Packages and Exception Handling using Java

Managing I/O: Streams, Byte Streams and Character Streams, Predefined Streams,
Reading console Input, Writing Console Output, Print Writer class.

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

● Inheritance –Definition
● Single Inheritance
● Benefits of inheritance
● Member access rules
● super classes
● Polymorphism
● Method overriding
● Using final with inheritance
● abstract classes and
● Base class object.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Definition
● Inheritance is the process of acquiring the properties by the sub
class ( or derived class or child class) from the super class (or base
class or parent class).
● When a child class(newly defined abstraction) inherits(extends) its
parent class (being inherited abstraction), all the properties and
methods of parent class becomes the member of child class.
● In addition, child class can add new data fields(properties) and
behaviors(methods), and
● It can override methods that are inherited from its parent class.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College
Inheritance of Engineering
Basics

The keyword extends is used to define inheritance in Java.

Syntax:-

class subclass-name extends superclass-name {


// body of the class
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Single Inheritance
-Derivation of a class from only one base class is called single inheritance.

//base class: A
class A{
//members of A
}
//Derived class syntax: B

class B extends A{

//members of B
}
Department of Computer Engineering
// Create a superclass. /* The subclass has access to all public members
class A { of its superclass. */
int i, j; subOb.i = 7;
void showij() { subOb.j = 8;
System.out.println("i and j: " + i + " " + j); subOb.k = 9;
}
} System.out.println("Contents of subOb: ");
// Create a subclass by extending class A.
class B extends A { subOb.showij();
int k; subOb.showk();
System.out.println();
void showk() {
System.out.println("k: " + k); System.out.println("Sum of i, j and k in subOb:");
}
void sum() { subOb.sum();
System.out.println("i+j+k: " + (i+j+k)); }
} }
} Contents of superOb:
class SimpleInheritance { i and j: 10 20
public static void main(String args[]) {
A superOb = new A(); Contents of subOb:
B subOb = new B();
i and j: 7 8
// The superclass may be used by itself.
k: 9
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of Sum of i, j and k in subOb:
superOb:"); i+j+k: 24
SNJB’s Late Sau. K. B. J. College of Engineering
The Benefits of Inheritance
● Software Reusability ( among projects )
○ Code ( class/package ) can be reused among the projects.
○ Ex., code to insert a new element into a table can be written once
and reused.
● Code Sharing ( within a project )
○ It occurs when two or more classes inherit from a single parent
class.
○ This code needs to be written only once and will contribute only
once to the size of the resulting program.
● Increased Reliability (resulting from reuse and sharing of code)
○ When the same components are used in two or more applications,
the bugs can be discovered more quickly.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
● Information Hiding
○ The programmer who reuses a software component needs only to
understand the nature of the component and its interface.
○ It is not necessary for the programmer to have detailed information
such as the techniques used to implement the component.
● Rapid Prototyping (quickly assemble from pre-existing components)
○ Software systems can be generated more quickly and easily by
assembling preexisting components.
○ This type of development is called Rapid Prototyping.
● Consistency of Interface(among related objects )
○ When two or more classes inherit from same superclass, the
behavior they inherit will be the same.
○ Thus , it is easier to guarantee that interfaces to similar objects are
similar.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
● Software Components
○ Inheritance enables programmers to construct reusable
components.
● Polymorphism and Frameworks (high-level reusable
components)
○ Normally, code reuse decreases as one moves up the levels of
abstraction.
● Lowest-level routines may be used in several different projects,
but higher-level routines are tied to a particular application.
● Polymorphism in programming languages permits the
programmer to generate high-level reusable components that
can be tailored to fit different applications by changes in their
low-level parts.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Single Inheritance Hierarchical Inheritance

A
X

B
A B C

Types of Inheritance
Multilevel Inheritance Multiple Inheritance / Not
Actually exists in Java

A A B

C C

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
//Multilevel Inheritance
//Single Inheritance class A{
}
class A{ class B extends A{
} }
class B extends A{ class C extends B{
} }

//Hierarchical Inheritance //Multiple Inheritance


class A{
} interface one{
class B extends A{ }
} interface two{
class C extends A{ }
} class A implements one, two{
}
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple Inheritance can be implemented by implementing multiple
interfaces not by extending multiple classes.
Example :
class B extends A implements C , D{

} OK

class C extends A extends B{ class C extends A ,B{ }

}
WRONG
WRONG
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

A Superclass Variable Can Reference a Subclass Object


When a reference to a subclass object is assigned to a
superclass variable, you will have access only to those
parts of the object defined by the superclass.

Department of Computer Engineering


A Superclass Variable Can Reference a Subclass Object
class Base
{ public void display()
{
System.out.println("Base class display is called");
}
}
class Derv1 extends Base
{ int i;
public void display()
{
System.out.println("Derv1 class display is called");
}
}
class Derv2 extends Base
{
public void display()
{
System.out.println("Derv2 class display is called");
}
}
A Superclass Variable Can Reference a Subclass Object
public class polymorhism {
public static void main(String[] args)
{
Base ptr; //Base class reference variable
Derv1 dl = new Derv1();
Derv2 d2 = new Derv2();
ptr = dl; // Base class variable is assigned reference of super class
ptr.i=10; // Error
System.out.println(ptr.i);// ptr contain reference of Derv1 object .>Error
ptr.display();
ptr = d2; // ptr contain reference of derv2 object
ptr.display(); Output:
} Derv1 class display is called
Derv2 class display is called
}
SNJB’s Late Sau. K. B. J. College of Engineering

Super Keyword
⚫ Subclass refers to its immediate superclass by using super
keyword.
⚫ super has two general forms.
○ First it calls the superclass constructor.
○ Second is used to access a member of the superclass that has
been hidden by a member of a subclass.
⚫ Using super to call superclass constructors
○ super (parameter-list);
○ parameter-list specifies any parameters needed by the
constructor in the superclass.
○ super( ) must always be the first statement executed inside a
subclass constructor.

Department of Computer Engineering


class Box { int i;
Box() { i =10;
System.out.println("Box() in super class "+i);
}
Box(int a){
System.out.println("Box(int a) in super class"); }
}
class BoxWeight extends Box { int i;
BoxWeight(){ i = 20; super. i = 30;
System.out.println("BoxWeight() in sub class " +i); }
}
class DemoBoxWeight{
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight();
}
}

Output:
Box() in super class
BoxWeight() in sub class
//Using super to call superclass //constructors
class Box {
Box() {
System.out.println("Box() in super class");
}
Box(int a){
System.out.println("Box(int a) in super class"); }
}
class BoxWeight extends Box {
BoxWeight(){
super(10);
System.out.println("BoxWeight() in sub class"); }
}
class DemoBoxWeight{
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight();
}
}

Output:
Box(int a) in super class
BoxWeight() in sub class
SNJB’s Late Sau. K. B. J. College of Engineering

● 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.
● Syntax: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.

Department of Computer Engineering


// 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) {
OUTPUT
super.i = a; // i in A i in superclass: 1
i = b; // i in B
} i in subclass: 2
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[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
SNJB’s Late Sau. K. B. J. College of Engineering
When Constructors Are Called

● In a class hierarchy, constructors are called in order of


derivation, from superclass to subclass.
● super(…) must be the first statement executed in a subclass’
constructor.
● If super(…) is not used, the default constructor of each
superclass will be executed.
○ Implicitly default form of super ( super() ) will be invoked in
each subclass to call default constructor of superclass.

Department of Computer Engineering


class A {
A() {
System.out.println ("Inside A's constructor.");
}
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
} Output:
class C extends B { Inside A’s constructor
C() { Inside B’s constructor
System.out.println("Inside C's constructor."); Inside C’s constructor
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
Member access rules
A subclass includes all of the members (default, public, protected) of its
superclass except private members.
class A{ class Protected{
private int v=10; public static void main(String args[]){
int d=20; B b=new B();
public int b=30; b.disp();
protected int p=40; C c=new C();
} c.show();
class B extends A{ System.out.println(c.d)
void disp(){ S.o.p(c.b)
System.out.println(“v value : S.o.p(c.p)
"+v); }
System.out.println(“d value : }
"+d); Output:
System.out.println(“b value : d value : 20
"+b);
b value : 30
System.out.println("p value :
"+p); p value : 40
} p value : 40
}
class C extends B{
void show(){
SNJB’s Late Sau. K. B. J. College of Engineering
Polymorphism

● Assigning multiple meanings to the same method name


● Implemented using late binding or dynamic binding (run-time
binding):
● It means, method to be executed is determined at execution time,
not at compile time.
● Polymorphism can be implemented in two ways
○ Overloading
○ Overriding
● When a method in a subclass has the same name, signature and
return type as a method in its superclass, then the method in the
subclass is said to be overridden the method in the superclass.
● By method overriding, subclass can implement its own behavior.
Department of Computer Engineering
//Overriding example class Override{
class A{ public static void main(String args[])
int i,j; {
A(int a,int b){ B subob=new B(3,4,5);
i=a; subob.show();
i=b; }
} }
void show(){
System.out.println(“i and j :”+i+” “+j); Output:
}
K: 5
}
class B extends A{
int k;
B(int a, int b, int c){
super(a,b);
k=c;
}
void show(){

System.out.println(“k=:”+k);
SNJB’s Late Sau. K. B. J. College of Engineering

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, the method to execute will be based upon the type of
the object being referred to at the time the call occurs. Not the
type of the reference variable.

Department of Computer Engineering


//Dynamic Method Dispatch
class Dispatch{
class A{ public static void main(String args[]){
void callme(){ A a=new A();
System.out.println(“Inside A’s callme B b=new B();
C c=new C();
method”);
} A r;
}
r=a;
class B extends A{
r.callme();
void callme(){
System.out.println(“Inside B’s callme r=b;
method”); r.callme();
}
r=c;
} r.callme();
class C extends A{ }
}
void callme(){
System.out.println(“Inside C’s callme
method”);
Output:
}
Inside A's callme method
} Inside B's callme method
Inside C's callme method
// Using run-time polymorphism. class Triangle extends Figure {
class Figure { Triangle(double a, double b) {
double dim1; super(a, b);
double dim2; }
Figure(double a, double b) { // override area for right triangle
dim1 = a; double area() {
dim2 = b; System.out.println("Inside Area for
} Triangle.");
return dim1 * dim2 / 2;
double area() {
}
System.out.println("Area for Figure is
undefined."); }
return 0;
} class FindAreas {
} public static void main(String args[]) {
class Rectangle extends Figure { Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Rectangle(double a, double b) {
Triangle t = new Triangle(10, 8);
super(a,b);
Figure figref;
} figref = r;
// override area for rectangle System.out.println("Area is " +
double area() { figref.area());
System.out.println("Inside Area for figref = t;
Rectangle.");
System.out.println("Area is " +
return dim1 * figref.area());
Inside Area for Rectangle.
dim2;
Area is 45 figref = f;
} Inside Area for Triangle. System.out.println("Area is " +
} Area is 40 figref.area());
Area for Figure is undefined. }
Area is 0 }
SNJB’s Late Sau. K. B. J. College of Engineering
Abstract Classes

● A method that has been declared but not defined is an abstract


method.
● Any class that contains one or more abstract methods must also be
declared abstract.
● You must declare the abstract method with the keyword abstract:
abstract type name (parameter-list);
● You must declare the class with the keyword abstract:
abstract class MyClass{
......
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Abstract Classes
● An abstract class is incomplete, It has “missing” method bodies.
● You cannot instantiate (create a new instance of) an abstract class
but you can create reference to an abstract class.
● Also, you cannot declare abstract constructors, or abstract static
methods.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

● You can declare a class to be abstract even if it does not contain


any abstract methods. This prevents the class from being
instantiated.
● An abstract class can also have concrete methods.
● You can extend (subclass) an abstract class.
● If the subclass defines all the inherited abstract methods, it is
“complete” and can be instantiated.
● If the subclass does not define all the inherited abstract methods,
it is also an abstract class.
Department of Computer Engineering
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
} Output:
class B extends A { B's implementation
void callme() { of callme.
System.out.println("B's implementation of callme.");
}
} This is a
class AbstractDemo { concrete method.
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
SNJB’s Late Sau. K. B. J. College of Engineering

Using final with Inheritance

The keyword final has three uses:


● To create a constant variable
● To prevent overriding
● To prevent inheritance

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Using final with Inheritance
1
To create a constant variable:
– 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.

class FinalDemo{
public static void main(String sree[]){
final int i=20;
System.out.println(i);
//i=i+1; can’t assign a value to final variable i
//System.out.println(i); cannot assign a value to final
variable i
}
} Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
2 To prevent overriding

To disallow a method from being overridden, specify final as a


modifier at the start of its declaration. Methods declared as final
cannot be overridden.
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!");
}
} Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
3 To prevent Inheritance
● To prevent a class from being inherited precede the class
declaration with final.
● Declaring a class as final implicitly declares all of its methods as
final, too.
● It is illegal to declare a class as both abstract and final 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
// ...
}
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

● Normally, Java resolves calls to methods dynamically, at run


time. This is called late binding.
● However, since final methods cannot be overridden, a call to
one can be resolved at compile time. This is called early
binding.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

The Object Class


● Object is a special class, defined by Java.
● Object is a superclass of all other classes.
● This means that a reference variable of type Object can
refer to an object of any other class.
● Object defines the following methods:

Department of Computer Engineering


Method Purpose
Object clone( ) Creates a new object that is the same
as the object being cloned.

boolean equals(Object object) Determines whether one object is


equal to another.

void finalize( ) Called before an unused object is


recycled.

Class getClass( ) Obtains the class of an object at run


time

int hashCode( ) Returns the hash code associated


with the invoking object.

void notify( ) Resumes execution of a thread


waiting on the invoking object.
Method Purpose
void notifyAll( ) Resumes execution of all
threads waiting on the invoking
object.
String toString( ) Returns a string that describes
the object
void wait( ) Waits on another thread of
void execution.
wait(long milliseconds)
void wait(long milliseconds,
int nanoseconds)
// Java program to demonstrate working of getClass()

public class Test {


public static void main(String[] args)
{
Object obj = new String("GeeksForGeeks");
Class c = obj.getClass();
System.out.println("Class of Object obj is : " +
c.getName());

Test t = new Test();


System.out.println(t.hashCode());

}
Output:
}
Class of Object obj is : java.lang.String
366712642

You might also like