M3
M3
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 {
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();
⮚ 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
● 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
{
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
}
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.
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();
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");
}
}
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);
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.