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

OOP with Java Module 3 Notes (1) (1)

The document discusses inheritance and interfaces in object-oriented programming, particularly in Java. It explains the concepts of superclasses and subclasses, how to use the 'extends' keyword for inheritance, and the importance of member access and method overriding. Additionally, it covers multilevel hierarchies, the execution order of constructors, and dynamic method dispatch, which allows for runtime polymorphism.

Uploaded by

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

OOP with Java Module 3 Notes (1) (1)

The document discusses inheritance and interfaces in object-oriented programming, particularly in Java. It explains the concepts of superclasses and subclasses, how to use the 'extends' keyword for inheritance, and the importance of member access and method overriding. Additionally, it covers multilevel hierarchies, the execution order of constructors, and dynamic method dispatch, which allows for runtime polymorphism.

Uploaded by

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

Module 3

Inheritance , Interfaces
Inheritance
Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications. Using
inheritance, you 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 members defined by the superclass and adds
its own, unique elements.
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.

To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
The general form of a class declaration that inherits a superclass is shown
here:

class subclass-name extends superclass-name


{ // body of class
}
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how, let’s begin with a short
example. 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.
​// 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));
​} }

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

​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

Member Access and Inheritance


Subclass includes all of the members of its superclass, it 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 subclasses.
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. This aspect of inheritance is quite
useful in a variety of situations.

Using super
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.

Using super to Call Superclass Constructors

A subclass can call a constructor defined by its superclass by use of the


following form of super:

super(arg-list);

Here, arg-list specifies any arguments needed by the constructor in the


superclass. super( ) must always be the first statement executed inside a
subclass’ constructor.
// 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; }
}
// A complete implementation of BoxWeight.
class Box {
private double width;
private double height;
private 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;
}
// 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;
}
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m; }
// default constructor
BoxWeight() {
super();
weight = -1; }
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m; }
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
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);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();

vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}}
This program generates the following 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
Volume of mybox3 is -1.0
Weight of mybox3 is -1.0
Volume of myclone is 3000.0
Weight of myclone is 34.3
Volume of mycube is 27.0
Weight of mycube is 2.0
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.
// 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);
}}
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

Creating a Multilevel Hierarchy

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.

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. In it, the subclass
BoxWeight is used as a superclass to create the subclass called Shipment.
Shipment inherits all of the traits of BoxWeight and Box, and adds a field
called cost, which holds the cost of shipping such a parcel.

Creating a Multilevel Hierarchy


// Extend BoxWeight to include shipping costs.
// Start with Box.
class Box {
private double width;
private double height;
private 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;
}
// 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;
}
}

// Add weight.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m; }
// default constructor
BoxWeight() {
super();
weight = -1; }
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m; }
}
// Add shipping costs.
class Shipment extends BoxWeight {
double cost;
// construct clone of an object
Shipment(Shipment ob) { // pass object to constructor
super(ob);
cost = ob.cost;
}
// constructor when all parameters are specified
Shipment(double w, double h, double d,
double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}
// default constructor
Shipment() {
super();
cost = -1; }
// constructor used when cube is created
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);
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);} }
The output of this program is shown here
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41

Volume of shipment2 is 24.0


Weight of shipment2 is 0.76
Shipping cost: $1.28
When Constructors Are Executed
When a class hierarchy is created, in what order are the constructors for the
classes that make up the hierarchy executed? For example, given a subclass
called B and a superclass called A, is A’s constructor executed before B’s, or
vice versa? The answer is that in a class hierarchy, constructors complete their
execution in order of derivation, from superclass to subclass. Further, 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 parameterless constructor of each superclass will be executed.
// Demonstrate when constructors are executed.
// 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.");
}}
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

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 its 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.
// 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);
}}
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);
}
}
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
Dynamic Method Dispatch
If there were nothing more to method overriding than a name space
convention, then it would be, at best, an interesting curiosity, but of little real
value. However, this is not the case. 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.
Dynamic method dispatch is important because this is how Java implements
run-time polymorphism. it is the type of the object being referred to (not the
type of the reference variable) that determines which version of an overridden
method will be executed.
// Dynamic Method Dispatch
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");
}
}
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
}
}
The output from the program is shown here:
Inside A's callme method
Inside B's callme method
Inside C's callme method
Using Abstract Classes
A class which is declared with the abstract keyword is known as an
abstract class in Java. It can have abstract and non-abstract methods (method
with the body).

Abstraction is a process of hiding the implementation details and showing


only functionality to the user.
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1.Abstract class (0 to 100%)


2.Interface (100%)
3.An abstract class must be declared with an abstract keyword.
4.It can have abstract and non-abstract methods.
5.It cannot be instantiated(creating new instances of objects to be used in a
program)
6.It can have constructors and static methods also.
7.It can have final methods which will force the subclass not to change the body
of the method.

To declare an abstract method, use this general form:


abstract type name(parameter-list);

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
} }
Using final with Inheritance

The keyword final has three uses. First, it can be used to create the equivalent
of a named constant.The other two uses of final apply to inheritance .
Here is an example of a final class:
final class A {
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//... }
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. Also, since arrays are implemented as classes, a variable of
type Object can also refer to any array.

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.
Interface In JAVA
An Interface in Java programming language is defined as an abstract type
used to specify the behavior of a class. An interface in Java is a blueprint of a
behavior. A Java interface contains static constants and abstract methods.
Defining an Interface
An interface is defined much like a class. This is a simplified general form of
an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//... return-type method-nameN(parameter-list); type final-varnameN = value;
}
Uses of Interfaces in Java
Uses of Interfaces in Java are mentioned below:
●It is used to achieve total abstraction.
●Since java does not support multiple inheritances in the case of class, by using
an interface it can achieve multiple inheritances.
●Any class can extend only 1 class but can any class implement an infinite
number of interface.
●It is also used to achieve loose coupling.
●Interfaces are used to implement abstraction.

The reason is, abstract classes may contain non-final variables, whereas
variables in the interface are final, public, and static.
// A simple interface

interface Player
{
final int id = 10;
int move();
}
Relationship Between Class and Interface
A class can extend another class similar to this an interface can extend another
interface. But only a class can extend to another interface, and vice-versa is
not allowed.
Difference Between Class and Interface
Although Class and Interface seem the same there have certain differences
between Classes and Interface. The major differences between a class and an
interface are mentioned below:

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}
// A class that implements the interface.
class TestClass implements In1 { // Implementing the capabilities of
interface.
public void display(){
System.out.println("Geek");
}
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Implementing Interfaces
The general form of a class that includes the implements clause looks like
this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
Advantages of Interfaces in Java

The advantages of using interfaces in Java are as follows:


1.Without bothering about the implementation part, we can achieve the security
of the implementation.
2.In Java, multiple inheritances are not allowed, however, you can use an
interface to make use of it as you can implement more than one interface.
Default Interface Methods
A default method lets you define a default implementation for an interface
method.

In other words, by use of a default method, it is now possible for an interface


method to provide a body, rather than being abstract.

During its development, the default method was also referred to as an


extension method.
A primary motivation for the default method was to provide a means by
which interfaces could be expanded without breaking existing code.

In the past, if a new method were added to a popular, widely used interface,
then the addition of that method would break existing code because no
implementation would be found for that new method. The default method
solves this problem by supplying an implementation that will be used if no
other implementation is explicitly provided. Thus, the addition of a default
method will not cause pre existing code to break. Another motivation for the
default method was the desire to specify methods in an interface that are,
essentially, optional, depending on how the interface is used.
An interface default method is defined similar to the way a method is defined
by a class.
The primary difference is that the declaration is preceded by the keyword
default.

For example, consider this simple interface:

public interface MyIF


{
// This is a "normal" interface method declaration.
// It does NOT define a default implementation.
int getNumber();
// This is a default method. Notice that it provides
// a default implementation.
default String getString()
{
return "Default String"}

You might also like