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

M3

OOPS With JAVA Module 3 BCS306A

Uploaded by

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

M3

OOPS With JAVA Module 3 BCS306A

Uploaded by

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

OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

MODULE-3

Inheritance: Inheritance, Using super, Creating a Multilevel Hierarchy, When Constructors Are
Called, Method Overriding, Dynamic Method Dispatch, Using Abstract Classes, Using final
with Inheritance, The Object Class.

Interfaces: Interfaces, Default Interface Methods, Use static Methods in an Interface, Private
InterfaceMethods.

Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. The idea behind inheritance in java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship. The class
which inherits the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent class). extends is
the keyword used to inherit the properties of a class.
Use of inheritance in java:
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax for Inheritance:
The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
Example for 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 {

Prof. Kavitha bDept of ISE,RNSIT Page 1


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
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

Prof. Kavitha bDept of ISE,RNSIT Page 2


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
The subclass B includes all of the members of its superclass, A. This is why subOb can
access i and j and call showij( ). Also, inside sum( ), i and j can be referred to directly, as if
they were part of B.
You can only specify one superclass for any subclass that you create. Java does not support
the inheritance of multiple superclasses into a single subclass.
Member Access and Inheritance
A subclass includes all of the members of its superclass, it cannot access those members of the
superclass that have been declared as private. 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;
}
}
class B extends A {// A's j is not accessible here.

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

Prof. Kavitha bDept of ISE,RNSIT Page 3


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
System.out.println("Total is " + subOb.total);
}
}
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.

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.
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " +
vol); System.out.println("Weight of weightbox is " +
weightbox.weight);
System.out.println();
plainbox = weightbox; // assign BoxWeight reference to Box reference
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight
member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box
objects.
Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference to the
weightbox object.
Creating a Multilevel Hierarchy :
One can inherit from a derived class thereby making this derived class the base class for the
new class.

Prof. Kavitha bDept of ISE,RNSIT Page 4


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

Refer class notes as well TB for examples.

When Constructors Are Called


Hierarchy constructor complete its execution in order of derivation from superclass to
subclass.
If super() is not used then the default constructors of each superclass is
executed. 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
The constructors are called in order of derivation. It makes sense that constructors are
executed in order of derivation. Because a superclass has no knowledge of any subclass, any
initialization it needs to perform is separate from and possibly prerequisite to any initialization
performed by the subclass. Therefore, it must be executed first.

Prof. Kavitha bDept of ISE,RNSIT Page 5


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

⮚ 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.
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;
}
void show() { // display k – this overrides show() in A
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

Prof. Kavitha bDept of ISE,RNSIT Page 6


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A.

⮚ Dynamic Method Dispatch


● 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.
● Restating an important principle: a superclass reference variable can refer to a subclass object.
Java uses this fact to resolve calls to overridden methods at run time.
● 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.
● When different types of objects are referred to, different versions of an overridden method will
be called. In other words, 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.
● Therefore, if a superclass contains a method that is overridden by a subclass, then when different
types of objects are referred to through a superclass reference variable, different versions of the
method is 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() {

Prof. Kavitha bDept of ISE,RNSIT Page 7


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
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
● This program creates one superclass called A and two subclasses of it, called B and C.
● Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type
A, B, and C are declared. Also, a reference of type A, called r, is declared. The program then in
turn assigns a reference to each type of object to r and uses that reference to invoke callme( ). As
the output shows, the version of callme( ) executed is determined by the type of object being
referred to at the time of the call. Had it been determined by the type of the reference variable, r,
you would see three calls to A’s callme( ) method.
⮚ Abstract Classes
● An abstract class is a class that is declared abstract—It can have abstract and non-abstract
methods (method with body). Abstract classes cannot be instantiated, but they can be subclassed.
That is, we cannot create an object for abstract classes.Abstraction is a process of hiding the
implementation details and showing only functionality to the user.
● Another way, it shows only important things to the user and hides the internal details for

Prof. Kavitha bDept of ISE,RNSIT Page 8


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
● To use an abstract class, you have to inherit it from another class, provide implementations to the
abstract methods in it.
● If you inherit an abstract class, you have to provide implementations to all the abstract methods
in it.
Abstract method

● Method that is declared without any body within an abstract class is called abstract method. The
method body will be defined by its subclass. Abstract method can never be final and static. Any
class that extends an abstract class must implement all the abstract methods declared by the super
class.
Syntax: abstract return_type function_name ();
abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){
System.out.println("drawing circle");}
}
class TestAbstraction {
public static void main(String args[]) {
Rectangle r = new Rectangle();
r.draw();
Shape s=new Circle();
s.draw();
}
}
Output:
drawing rectangle
drawing circle

Prof. Kavitha bDept of ISE,RNSIT Page 9


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
Example of Abstract classes with constructors

abstract class Bike

{
Bike(){
System.out.println("bike is created");
}
abstract void run();
}
void changeGear(){
System.out.println("gear changed");
}
}
class Honda extends
Bike{ void run(){
System.out.println("running safely..");
}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output:
bike is created
running safely..
gear changed
When to use Abstract Methods & Abstract Class?
● Abstract methods are usually declared where two or more subclasses are expected to do a similar
thing in different ways through different implementations. These subclasses extend the same
Abstract class and provide different implementations for the abstract methods.
● Abstract classes are used to define generic types of behaviours at the top of an object -oriented
programming class hierarchy, and use its subclasses to provide implementation details of the

Prof. Kavitha bDept of ISE,RNSIT Page 10


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
abstract class.

⮚ Using final with Inheritance


The keyword final has three uses. First, it can be used to create the equivalent of a named
constant. This use was described in the preceding chapter. The other two uses of final apply to
inheritance.
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!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do
so, a compile-time error will result.
Methods declared as final can sometimes provide a performance enhancement: The compiler is
free to inline calls to them because it “knows” they will not be overridden by a subclass.
When a small final method is called, often the Java compiler can copy the bytecode for the
subroutine directly inline with the compiled code of the calling method, thus eliminating the
costly overhead associated with a method call.
Inlining is only an option with final methods. 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.
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.
Prof. Kavitha bDept of ISE,RNSIT Page 11
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
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:
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.
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.
● Object defines the following methods, which means that they are available in every object.

● The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
● However, notice two methods now: 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.
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.
Prof. Kavitha bDept of ISE,RNSIT Page 12
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

Interfaces
Interface is an abstract type that can contain only the declarations of methods and
constants. Interfaces are syntactically similar to classes, but they do not contain instance
variables, and their methods are declared without any body.
Any number of classes can implement an interface. One class may implement many
interfaces. By providing the interface keyword, Java allows you to fully utilize the ―one
interface,

multiple methods aspect of polymorphism. Interfaces are alternative means for multiple
inheritance in Java. 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;
}
Few key-points about interface:
When no access specifier is mentioned for an interface, then it is treated as default and the
interface is only available to other members of the package in which it is declared. When
an interface is declared as public, the interface can be used by any other code.
All the methods declared are abstract methods and hence are not defined inside interface.
But, a class implementing an interface should define all the methods declared inside the
interface.
Variables declared inside of interface are implicitly final and static, meaning they cannot
be changed by the implementing class.

Prof. Kavitha bDept of ISE,RNSIT Page 13


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
All the variables declared inside the interface must be initialized.
All methods and variables are implicitly public.

Default interface: Default interface methods were introduced in Java 8 to allow interfaces to
provide a default implementation for methods. Prior to Java 8, interfaces could only declare
method signatures, and implementing classes were required to provide concrete implementations
for all methods. With default interface methods, you can now include method implementations in
an interface, and classes that implement the interface can choose to override or use the default
implementation.

Declaration:
In an interface, you can provide a default implementation for a method using the default keyword.
Syntax:
interface MyInterface {
// Abstract method (no implementation required for implementing classes)
void regularMethod();

// Default method with implementation


default void defaultMethod() {
// Implementation code
}
}
Usage in Implementing Classes:
Classes that implement the interface can choose to override the default method or use it as is.
If a class chooses to override, it provides its own implementation. If not, it inherits the default
implementation.
class MyClass implements MyInterface {
// Regular method must be implemented
@Override
public void regularMethod() {
// Implementation code
}

// Default method can be overridden if needed

Prof. Kavitha bDept of ISE,RNSIT Page 14


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
@Override
public void defaultMethod() {
// Custom implementation or use the default
}
}
Advantages:
Backward Compatibility: Existing interfaces can evolve without breaking existing implementations. New
methods can be added with default implementations.
Code Reusability: Default methods allow for sharing common implementations across multiple classes.
Multiple Inheritance:

Java interfaces can now have multiple methods with default implementations.
If a class implements multiple interfaces with conflicting default methods, it must provide its own
implementation to resolve the conflict.
interface InterfaceA {
default void commonMethod() {
System.out.println("InterfaceA's implementation");
}
}

interface InterfaceB {
default void commonMethod() {
System.out.println("InterfaceB's implementation");
}
}

class MyClass implements InterfaceA, InterfaceB {


// To resolve the conflict, provide a custom implementation

public void commonMethod() {


System.out.println("Custom implementation");
}
}
Default interface methods provide a way to extend interfaces in a flexible manner, allowing for
the addition of new methods without breaking existing code. However, careful consideration is

Prof. Kavitha bDept of ISE,RNSIT Page 15


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
needed when dealing with multiple interfaces to avoid conflicts and ambiguity in method
resolution.

Use static methods in an interface


Static methods in interfaces were introduced in Java 8, and they provide a way to define utility methods
related to the interface without requiring an instance of the interface.
In an interface, you can declare a static method using the static keyword.
interface MyInterface {
// Abstract method (no implementation required for implementing classes)
void regularMethod();

// Static method with implementation


static void staticMethod() {
// Implementation code
}
}

The static method can be called using the interface name, without the need for an instance of the
interface.

interface MathOperation {
// Abstract method
int operate(int a, int b);

// Static method to calculate square


static int square(int a) {
return a * a;
}
}

class Calculator implements MathOperation {


// Implementation of the abstract method

public int operate(int a, int b) {


return a + b;

Prof. Kavitha bDept of ISE,RNSIT Page 16


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();

// Using the static method from the interface


int squaredValue = MathOperation.square(5);
System.out.println("Square of 5: " + squaredValue);

// Using the implemented method from the interface


int result = calculator.operate(3, 4);
System.out.println("Result of operation: " + result);
}
}
Private Interface Methods:
In Java 9, we can create private methods inside an interface. Interface allows us to declare private
methods that help to share common code between non-abstract methods.
Before Java 9, creating private methods inside an interface cause a compile time error.

interface Sayable{
default void say() {
saySomething();
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String[] args) {
Sayable s = new PrivateInterface();
s.say();
}
}
Prof. Kavitha bDept of ISE,RNSIT Page 17
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

Output:
Hello... I'm private method
Rules For using Private Methods in Interfaces
● Private interface method cannot be abstract and no private and abstract modifiers together.
● Private method can be used only inside interface and other static and non-static interface
methods.
● Private non-static methods cannot be used inside private static methods.
● We should use private modifier to define these methods and no lesser accessibility than private
modifier.

Prof. Kavitha bDept of ISE,RNSIT Page 18

You might also like