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

Java Module4 Bplck205c

Module 4 of the Java Programming course focuses on inheritance, explaining its basics, member access, and the use of the 'super' keyword. It covers multilevel hierarchies, constructor invocation order, method overriding, dynamic method dispatch, and abstract classes. The module provides examples to illustrate these concepts, emphasizing the importance of inheritance in object-oriented programming.

Uploaded by

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

Java Module4 Bplck205c

Module 4 of the Java Programming course focuses on inheritance, explaining its basics, member access, and the use of the 'super' keyword. It covers multilevel hierarchies, constructor invocation order, method overriding, dynamic method dispatch, and abstract classes. The module provides examples to illustrate these concepts, emphasizing the importance of inheritance in object-oriented programming.

Uploaded by

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

Basis of Java Programming Module-4 BPLCK205C

MODULE-4

Chapter 1: Inheritance

Syllabus:
Chapter 1:
1. Inheritance Basics
(i) Member Access and Inheritance
(ii) A Superclass Variable Can reference a Subclass Object
2. Using Super
(i) Using super to Call Superclass Constructor
(ii) A Second Use for super
3. Creating a Multilevel Hierarchy
4. When Constructors are Called
5. Method Overriding
6. Dynamic Method Dispatch
7. Using Abstract Classes
8. Using final with Inheritance
(i) Using final to Prevent Overriding
(ii) Using final to Prevent Inheritance
9. The Object Class

Prof. Ashwini G Dept. of CS&E, MITT Page 1


Basis of Java Programming Module-4 BPLCK205C

Chapter 1: Inheritance
 Inheritance is the process by which one class acquires the properties of another
class. This is important because it supports the concept of hierarchical classification.
 The class that is inherited is called superclass. The class that is inheriting the
properties is called subclass.
 Therefore the subclass is the specialized version of the superclass. The subclass
inherits all the instance variable and methods, and adds its own code.

1. Inheritance Basics
 The properties from superclass to the subclass are inherited using the "extends"
keyword.
 General form of inheritance

// General form of Inheritance


class subclass_name extends superclass_name
{
// body of the subclass
}

 The following program creates a superclass called A and a subclass called B. Notice
how the keyword extends is used to create a subclass of A.

// A simple example of inheritance.


// 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));
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 2


Basis of Java Programming Module-4 BPLCK205C

class SimpleInheritance
{
public static void main(String args[])
{
/* subclass object creation, which acquires Contents of b:
all the properties of the superclass*/ i and j: 7 8
B b = new B(); k: 9
/* The subclass has access to all public Sum of i, j and k in b:
members of its superclass. */ i+j+k: 24
b.i = 7;
b.j = 8;
b.k = 9;
System.out.println("Contents of b: ");
b.showij();
b.showk();
System.out.println("Sum of i, j and k in b:");
b.sum();
}
}

(i) Member Access and Inheritance


 Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private.
 The private members of the class are accessed by the members of that class only,
but are not accessed by the code outside that class in which they are declared.
 For example, consider the following simple class hierarchy:

/* In a class hierarchy, private members remain


private to their class.
This program contains an error and will not
compile.
*/
// 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;
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 3


Basis of Java Programming Module-4 BPLCK205C

// A's j is not accessible here.


class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}
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);
}
}

Note:
 This program will not compile because the reference to j inside the sum( )
method of B causes an access violation. Since j is declared as private, it is only
accessible by other members of its own class. Subclasses have no access to it.

(ii) A Superclass Variable Can Reference a Subclass Object


 A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass. You will find this aspect of inheritance quite useful
in a variety of situations.
 When a reference to a subclass object is assigned to a superclass reference
variable, you will have access only to those parts of the object defined by the
superclass.

Prof. Ashwini G Dept. of CS&E, MITT Page 4


Basis of Java Programming Module-4 BPLCK205C

class Box
{
double width,height,depth;
}
class Boxweight extends Box
{
double weight;
Boxweight(double x, double y, double z, double a)
{
width=x; height=y; depth=z; weight=a;
}
void volume()
{
System.out.println("The volume is :"+(width*height*depth));
}
}
class BoxDemo
{
//creating superclass object
public static void main(String args[])
{
Box b=new Box();
//creating the subclass object
Boxweight bw=new Boxweight(2,3,4,5);
bw.volume();
//assigning the subclass object to the superclass object
b=bw; // b has been created with its own data, in which weight is not a member

System.out.println ("The weight is :"+b.weight);


// here it raises error, cannot find symbol
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 5


Basis of Java Programming Module-4 BPLCK205C

2. 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(uses).
 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.

(i) Using super to Call Superclass Constructors


 A subclass can call the constructor of the superclass by using the super keyword
in the following form.
super(arg-list);

 Here, arg-list, is the list of the arguments in the superclass constructor. Yhis must
be the first statement inside the subclass constructor.
 For example:

// BoxWeight now uses super to initialize its Box attributes.


class Box
{
double width,height,depth;
//superclass constructor
Box(double x, double y, double z)
{
width=x;height=y;depth=z;
}
}
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;
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 6


Basis of Java Programming Module-4 BPLCK205C

(ii) Using super to access the super class members.(A second use for super)
 The second form of super acts somewhat like this, except that it always refers to
the superclass of the subclass in which it is used. 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.
 Consider this simple class hierarchy:

// 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();
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 7


Basis of Java Programming Module-4 BPLCK205C

3. Creating a Multilevel Hierarchy


 Up to this point, we have been using simple class hierarchies that consist of only a
superclass and a subclass. However, you can build hierarchies that contain as many
layers of inheritance as you like. As mentioned, it is perfectly acceptable to use a
subclass as a superclass of another.
 For example, given three classes called A, B, and C, C can be a subclass of B, which is
a subclass of A. When this type of situation occurs, each subclass inherits all of the
traits found in all of its superclasses.
 In this case, C inherits all aspects of B and A. To see how a multilevel hierarchy can
be useful, consider the following program.

class A
{
void methodA()
{
System.out.println("This is the method of A");
}
}
//Multi Level Inheritance//class b extends the super class A
class B extends A
{
void methodB()
{
System.out.println("This is the method of B");
}
}//class C extends the super class B
class C extends B
{
void methodC()
{
System.out.println("This is the method of C");
}
}
class Hierarchy
{
public static void main(String args[])
{
C cobj=new C();
OUTPUT
cobj.methodA();
This is the method of A
cobj.methodB();
cobj.methodC(); This is the method of B
} This is the method of C
}

Prof. Ashwini G Dept. of CS&E, MITT Page 8


Basis of Java Programming Module-4 BPLCK205C

4. When Constructors are Called


 When a class hierarchy is created, in what order are the constructors for the classes
that make up the hierarchy called? For example, given a subclass called B and a
superclass called A, is A’s constructor called before B’s, or vice versa? The answer is
that in a class hierarchy, constructors are called in order of derivation, from
superclass to subclass.
 If super( ) is not used, then the default or parameterless constructor of each
superclass will be executed.

// Demonstrate when constructors are called.


// 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.");
}
} OUTPUT
// Create another subclass by extending B. Inside A's constructor.
class C extends B
Inside B's constructor.
{
C() Inside C's constructor.
{
System.out.println("Inside C's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 9


Basis of Java Programming Module-4 BPLCK205C

5. Method Overriding
 In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass.
 When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden.
 Consider the following example:

// Method overriding.
class A
{
void disp()
{
System.out.println("This is the class A method");
}
}
// extending the superclass properties
OUTPUT
class B extends A
This is the class B method
{
void disp()
{
System.out.println("This is the class B method");
}
}
// main class
class OverRide
{
public static void main(String args[])
{
B b=new B();
b.disp(); // super class method is hidden, subclass method is invoked
}
}

6. 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. Dynamic method dispatch
is important because this is how Java implements run-time polymorphism.
 A superclass reference variable can refer to a subclass object. Java uses this fact
to resolve calls to overridden methods at run time.

Prof. Ashwini G Dept. of CS&E, MITT Page 10


Basis of Java Programming Module-4 BPLCK205C

 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
class A {
void callme()
{
System.out.println("Inside A's callme method");
}
} OUTPUT
class B extends A Inside A's callme method
{ Inside B's callme method
// override callme()
Inside C's callme method
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");
}
}
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
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 11


Basis of Java Programming Module-4 BPLCK205C

7. Using Abstract Classes


 Sometimes it may be need by the superclass to define the structure of the every
method without implementing it. The subclass can fill or implement the method
according to its requirements. This kind of situation can come into picture
whenever the superclass unable to implement the meaningful implementation of the
method.

GENERAL FORM
abstract type name (parameter-list);

 A method without body (no implementation) is known as abstract method.


 A method must always be declared in an abstract class, or we can say that if a class
has an abstract method, it should be declared abstract as well.
 If a regular class extends an abstract class, then the class must have to implement
all the methods of abstract parent class or it has to be declared abstract as well.
 Abstract classes cannot be initiated, means we can’t create an object of abstract
class.

// 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 of callme.
{ This is a concrete method.
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();
}
}

Prof. Ashwini G Dept. of CS&E, MITT Page 12


Basis of Java Programming Module-4 BPLCK205C

8. Using Final with Inheritance


 The keyword final has three uses.
1. It is used to create the equivalent of a named constant.
Ex: final int speed=120;
2. Using final to prevent overriding.
3. Using final to prevent Inheritance.

(i) Using final to Prevent Overriding


 While method overriding is one of Java’s most powerful features, there will be
times when you will want to prevent it from occurring.
 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. The following fragment
illustrates final:

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!");
}
}

(ii) Using final to Prevent Inheritance


 Sometimes you will want to prevent a class from being inherited. To do this,
precede the class declaration with final.
 Declaring a class as final implicitly declares all of its methods as final, too.
 As you might expect, 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.
 Here is an example of a final class:

Prof. Ashwini G Dept. of CS&E, MITT Page 13


Basis of Java Programming Module-4 BPLCK205C

final class A
{
// ...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
// ...
}

 As the comments imply, it is illegal for B to


inherit A since A is declared as final.

9. The Object Class


 There is one special class, Object, defined by Java. All other classes are subclasses of
Object. That is, 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, which means that they are available in every
object

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
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 execution.
void wait(long milliseconds)
void wait (long milliseconds,
I int nanoseconds)

Prof. Ashwini G Dept. of CS&E, MITT Page 14

You might also like