Bcs306a Java Module 3
Bcs306a Java Module 3
INHERITANCE BASICS
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
The syntax of Java Inheritance
The extends keyword indicates for making a new class that derives from an existing class.
Terms used in Inheritance
[Link],SVCE 1
OOPS WITH JAVA (BCS306A) MODULE 3
INHERITANCE EXAMPLES
EXAMPLE 1:
[Link],SVCE 2
OOPS WITH JAVA (BCS306A) MODULE 3
}
}
In the above example:
The Shape class is the parent class (superclass) with a property for color and a method for
drawing.
The Circle class is a child class (subclass) that inherits from Shape. It also has an additional
property for the radius and a method to calculate the area of the circle.
In the main method, an instance of the Circle class is created (myCircle). We can use methods
from both the Shape class and the Circle class for this object.
This example demonstrates how inheritance can be used to model relationships between
different types of shapes, with common properties and behaviors in the superclass and
specialized properties and behaviors in the subclass.
EXAMPLE 2:
// Create a superclass.
class A {
int i, j;
void showij()
{
[Link]("i and j: " + i + " " + j);
}
}
void sum()
{
[Link]("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
[Link],SVCE 3
OOPS WITH JAVA (BCS306A) MODULE 3
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
[Link]("Contents of superOb: ");
[Link]();
[Link]();
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
TYPES OF INHERITANCE
There are five types of inheritance, they are:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
On the basis of class, there can be three types of inheritance in java:
[Link],SVCE 4
OOPS WITH JAVA (BCS306A) MODULE 3
In java programming, multiple and hybrid inheritance is supported through interface only.
SINGLE INHEITANCE:
As the name suggests, this type of inheritance occurs for only a single class. Only one class is
derived from the parent class.
In this type of inheritance, the properties are derived from a single parent class and not more
than that.
As the properties are derived from only a single base class the reusability of a code is
facilitated along with the addition of new features.
The flow diagram of a single inheritance is shown below:
Two classes Class A and Class B are shown in Figure, where Class B inherits the properties of Class
A.
EXAMPLE OF SINGLE INHERITANCE:
class Shape
{
public void draw() {
[Link]("Drawing a shape");
}
}
class Rectangle extends Shape
{
public void drawRectangle() {
[Link]("Drawing a rectangle");
}
}
public class SingleInheritance
{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle();
[Link](); // Inherited from Shape
[Link](); // Specific to Rectangle
[Link],SVCE 5
OOPS WITH JAVA (BCS306A) MODULE 3
}
}
Output:
Drawing a shape
Drawing a rectangle
MULTILEVEL INHERITANCE
The multi-level inheritance includes the involvement of at least two or more than two classes.
One class inherits the features from a parent class and the newly created sub-class becomes
the base class for another new class.
As the name suggests, in the multi-level inheritance the involvement of multiple base classes
is there.
In the multilevel inheritance in java, the inherited features are also from the multiple base
classes as the newly derived class from the parent class becomes the base class for another
newly derived class.
The flow diagram of a multilevel inheritance is shown below:
From the flow diagram, we can observe that Class B is a derived class from Class A, and Class C is
further derived from Class B.
EXAMPLE OF MULTILEVEL INHERITANCE
class Vehicle
{
public void move() {
[Link]("Vehicle is moving");
}
}
[Link],SVCE 6
OOPS WITH JAVA (BCS306A) MODULE 3
Output:
Vehicle is moving
Car is accelerating
SportsCar is boosting
HIERARCHICAL INHERITANCE
The type of inheritance where many subclasses inherit from one single class is known as
Hierarchical Inheritance.
Hierarchical Inheritance a combination of more than one type of inheritance.
It is different from the multilevel inheritance, as the multiple classes are being derived from
one superclass.
These newly derived classes inherit the features, methods, etc, from this one superclass. This
process facilitates the reusability of a code and dynamic polymorphism (method overriding).
The flow diagram of a Hierarchical inheritance is shown below:
[Link],SVCE 7
OOPS WITH JAVA (BCS306A) MODULE 3
In Figure, we can observe that the three classes Class B, Class C, and Class D are inherited from the
single Class A. All the child classes have the same parent class in hierarchical inheritance.
EXAMPLE OF HIERARCHICAL INHERITANCE
class Shape
{
public void draw() {
[Link]("Drawing a shape");
}
}
[Link],SVCE 8
OOPS WITH JAVA (BCS306A) MODULE 3
[Link](); // Specific to Square
}
}
Output:
Drawing a shape
Drawing a circle
Drawing a shape
Drawing a square
MULTIPLE INHERITANCE
Multiple inheritances is a type of inheritance where a subclass can inherit features from more
than one parent class.
Multiple inheritances should not be confused with multi-level inheritance, in multiple
inheritances the newly derived class can have more than one superclass.
And this newly derived class can inherit the features from these superclasses it has inherited
from, so there are no restrictions.
In java, multiple inheritances can be achieved through interfaces.
The flow diagram of a multiple inheritance is shown below:
Figure shows that Class C is derived from the two classes Class A and Class B. In other words it can
be described that subclass C inherits properties from both Class A and B.
HYBRID INHERITANCE
Hybrid inheritance is a combination of more than two types of inheritances single and
multiple.
It can be achieved through interfaces only as multiple inheritance is not supported by Java.
However, it is important to note that Hybrid inheritance does not necessarily require the use
of Multiple Inheritance exclusively.
[Link],SVCE 9
OOPS WITH JAVA (BCS306A) MODULE 3
It can be achieved through a combination of Multilevel Inheritance and Hierarchical
Inheritance with classes, Hierarchical and Single Inheritance with classes.
Therefore, it is indeed possible to implement Hybrid inheritance using classes alone, without
relying on multiple inheritance type.
The flow diagram of hybrid inheritance is shown below:
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.
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 major advantage of inheritance is that once you have created a superclass that defines the
attributes common to a set of objects, it can be used to create any number of more specific
subclasses.
Each subclass can precisely tailor its own classification.
EXAMPLE:
[Link],SVCE 10
OOPS WITH JAVA (BCS306A) MODULE 3
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String args[])
{
B subOb = new B();
[Link](10, 12);
[Link]();
[Link]("Total is " + [Link]);
}
}
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.
USING SUPER
There will be times when you will want to create a superclass that keeps the details of its
implementation to itself (that is, that keeps its data members private).
In this case, there would be no way for a subclass to directly access or initialize these variables
on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java
provides a solution to this problem.
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.
In Java, the super keyword is used to refer to the immediate parent class object. It is often
used to access the members (fields or methods) of the superclass when there is a need to
differentiate between the superclass and the subclass with the same name.
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.
Example:
class Animal
{
Animal() {
[Link],SVCE 11
OOPS WITH JAVA (BCS306A) MODULE 3
[Link]("Animal constructor");
}
}
Output:
Animal constructor
Dog constructor
Example:
class Animal
{
String sound = "Animal Sound";
void makeSound() {
[Link](sound);
}
}
[Link],SVCE 12
OOPS WITH JAVA (BCS306A) MODULE 3
[Link]();
Output:
Animal Sound
Animal Sound
Bark
[Link],SVCE 13
OOPS WITH JAVA (BCS306A) MODULE 3
void draw() {
[Link]("Drawing a circle");
}
void calculateArea() {
[Link]("Calculating area of a circle");
}
}
void calculateArea() {
[Link]("Calculating area of a rectangle");
}
}
[Link]();
[Link]();
}
}
Output:
Drawing a circle
Calculating area of a circle
Drawing a rectangle
Calculating area of a rectangle
[Link],SVCE 14
OOPS WITH JAVA (BCS306A) MODULE 3
The answer is that in a class hierarchy, constructors are called 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.
The following program illustrates when constructors are executed:
Example:
// Demonstrate when constructors are called.
// Create a super class.
class A
{
A( )
{
[Link]("Inside A's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}
Output:
[Link],SVCE 15
OOPS WITH JAVA (BCS306A) MODULE 3
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 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.
Example:
// Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
[Link]("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()
{
[Link]("k: " + k);
}
}
class Override
{
[Link],SVCE 16
OOPS WITH JAVA (BCS306A) MODULE 3
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}
Output:
k: 3
Method overriding occurs only when the names and the type signatures of the two methods are
identical. If they are not, then the two methods are simply overloaded.
Example:
// Dynamic Method Dispatch
class A
{
void callme()
{
[Link]("Inside A's callme method");
}
}
[Link],SVCE 17
OOPS WITH JAVA (BCS306A) MODULE 3
class B extends A
{
// override callme()
void callme()
{
[Link]("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme()
{
[Link]("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
[Link](); // calls A's version of callme
r = b; // r refers to a B object
[Link](); // calls B's version of callme
r = c; // r refers to a C object
[Link](); // calls C's version of callme
}
}
Output:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
[Link],SVCE 18
OOPS WITH JAVA (BCS306A) MODULE 3
USING ABSTRACT CLASSES
Data abstraction is the process of hiding certain details and showing only essential information
to the user. Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is a non-access modifier, used for classes and methods.
Abstract class is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
Abstract method can only be used in an abstract class, and it does not have a body. The body
is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods.
To declare an abstract method, use this general form:
abstract type name(parameter-list);
As you can see, no method body is present.
Any class that contains one or more abstract methods must also be declared abstract.
To declare a class abstract, you simply use the abstract keyword in front of the class keyword
at the beginning of the class declaration. There can be no objects of an abstract class.
That is, an abstract class cannot be directly instantiated with the new operator. Such objects
would be useless, because an abstract class is not fully defined. Also, you cannot declare
abstract constructors, or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract methods in the
superclass, or be itself declared abstract.
Example:
// A Simple demonstration of abstract.
abstract class A
{
abstract void callme();
class B extends A
{
void callme()
{
[Link]("B's implementation of callme.");
}
}
class AbstractDemo
{
[Link],SVCE 19
OOPS WITH JAVA (BCS306A) MODULE 3
public static void main(String args[])
{
B b = new B();
[Link]();
[Link]();
}
}
Notice that no objects of class A are declared in the program. As mentioned, it is not possible to
instantiate an abstract class. One other point: class A implements a concrete method called callmetoo(
). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.
Although abstract classes cannot be used to instantiate objects, they can be used to create object
references, because Java’s approach to run-time polymorphism is implemented through the use of
superclass references. Thus, it must be possible to create a reference to an abstract class so that it can
be used to point to a subclass object.
class A
{
final void meth()
{
[Link]("This is a final method.");
}
}
class B extends A
{
void meth() { // ERROR! Can't override.
[Link]("Illegal!");
}
}
[Link],SVCE 20
OOPS WITH JAVA (BCS306A) MODULE 3
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-
time error will result.
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
Consider two methods equals( ) and toString( ).
The equals( ) method compares the contents of two objects. It returns true if the objects are
equivalent, and false otherwise. The precise definition of equality can vary, depending on the
type of objects being compared.
[Link],SVCE 21
OOPS WITH JAVA (BCS306A) MODULE 3
The toString( ) method returns a string that contains a description of the object on which it is
called. Also, this method is automatically called when an object is output using println( ).
Many classes override this method. Doing so allows them to tailor a description specifically
for the types of objects that they create.
[Link],SVCE 22
OOPS WITH JAVA (BCS306A) MODULE 3
CHAPTER – 2
INTERFACES
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.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction and
multiple inheritances in Java using Interface. In other words, you can say that interfaces can
have abstract methods and variables. It cannot have a method body. Java Interface also
represents the IS-A relationship.
Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
Once interface is defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation. By
providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
Interfaces are designed to support dynamic method resolution at run time.
DEFINING AN INTERFACE
An interface is defined much like a class. This is the 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;
}
When no access specifier is included, then default access results, and the interface is only
available to other members of the package in which it is declared.
When it is declared as public, the interface can be used by any other code. In this case, the
interface must be the only public interface declared in the file, and the file must have the same
name as the interface.
name is the name of the interface, and can be any valid identifier. The methods that are
declared have no bodies. They end with a semicolon after the parameter list. They are,
essentially, abstract methods; there can be no default implementation of any method specified
within an interface.
[Link],SVCE 23
OOPS WITH JAVA (BCS306A) MODULE 3
Each class that includes an interface must implement all of the methods. Variables can be
declared inside of interface declarations.
They are implicitly final and static, meaning they cannot be changed by the implementing
class. They must also be initialized. All methods and variables are implicitly public.
IMPLEMENTING INTERFACES
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. If a
class implements two interfaces that declare the same method, then the same method will be
used by clients of either interface.
The methods that implement an interface must be declared public. Also, the type signature of
the implementing method must match exactly the type signature specified in the interface
definition.
EXAMPLE:
interface Callback
{
void callback(int param);
}
void nonIfaceMeth()
{
[Link]("Classes that implement interfaces " + "may also define other members,
too.");
}
}
class TestIface
{
[Link],SVCE 24
OOPS WITH JAVA (BCS306A) MODULE 3
public static void main(String args[])
{
Callback c = new Client();
[Link](42);
}
}
Output:
callback called with 42
Abstract Methods are the methods without a body (implementation). They are the core
methods that implementing classes must provide concrete implementations for.
Default Method is a method with the default keyword preceding its declaration. It includes a
default implementation within the interface itself. Classes that implement the interface can
choose to use the default implementation or override it with their own.
EXAMPLE:
// Define an interface with a default method
interface Vehicle
{
[Link],SVCE 25
OOPS WITH JAVA (BCS306A) MODULE 3
void start(); // Abstract method
void stop(); // Another abstract method
@Override
public void stop() {
[Link]("Car is stopping.");
}
[Link],SVCE 26
OOPS WITH JAVA (BCS306A) MODULE 3
}
In this example, the Vehicle interface has a default method named honk(). The Car class implements
this interface but does not provide an explicit implementation for the honk() method. Since it's a
default method, the interface provides a default implementation that can be used by any class
implementing the interface. The Car class can still override the honk() method if needed.
When you run the InterfaceExample class, you'll see that the honk() method is called on the myCar
instance, and it prints "Vehicle is honking." This demonstrates the use of default methods in
interfaces.
Syntax
interface InterfaceName {
// Abstract method(s)
void abstractMethod();
EXAMPLE:
interface MathOperation
{
// Abstract method
int operate(int a, int b);
[Link],SVCE 27
OOPS WITH JAVA (BCS306A) MODULE 3
[Link],SVCE 28
OOPS WITH JAVA (BCS306A) MODULE 3
Private methods can be added to interfaces in Java.
Private methods can be implemented static or non-static.
This means that in an interface we are able to create private methods to encapsulate code from
both default and static public method signatures.
EXAMPLE:
public interface Foo {
bar() is able to make use of the private method baz() by calling it from it’s default method.
Next, let’s add a statically defined private method to our Foo interface:
Within the interface, other statically defined methods can make use of these private static methods.
Finally, let’s call the defined default and static methods from a concrete class:
[Link],SVCE 29
OOPS WITH JAVA (BCS306A) MODULE 3
The output is the string “Hello world!” from the call to the bar() method and “Hello static world!”
from the call to the buzz() method.
[Link],SVCE 30