0% found this document useful (0 votes)
6 views20 pages

Lect 5+6

The document covers key concepts in Java including method overriding, overloading, and interfaces. It explains how subclasses can redefine inherited methods, the rules for method overriding, and the significance of interfaces in achieving abstraction and multiple inheritance. Additionally, it discusses polymorphism, its types, and provides examples to illustrate these concepts.

Uploaded by

Sayed Ghazal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views20 pages

Lect 5+6

The document covers key concepts in Java including method overriding, overloading, and interfaces. It explains how subclasses can redefine inherited methods, the rules for method overriding, and the significance of interfaces in achieving abstraction and multiple inheritance. Additionally, it discusses polymorphism, its types, and provides examples to illustrate these concepts.

Uploaded by

Sayed Ghazal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Lectures 5+6

Outline
• Java overriding
• Java overloading
• Interface in Java
• The relationship between classes and interfaces
• Multiple inheritance in Java by interface
• Interface inheritance
• Nested Interface in Java
• Abstraction
• Polymorphism

1
Java – Overriding:
You saw how the subclass inherits the variables and functions in the superclass. And I also
learned that the Subclass can redefine any function inherited from the Superclass, provided
that it is not defined as final, and write the word @Override before defining it again in order
to avoid problems when compiling the code.

Override: It means defining the function that the Subclass inherited from the Superclass again.
This new function is similar to the inherited function in terms of form only, that is, it has the
same name, type, and number of parameters, but its content is different.

The real goal of overriding is to allow the subclass to define functions as it needs.
Example:
Country.java
public class Country {
public void language( ) {
System.out.println("English");
}
}

Australia.java
public class Australia extends Country {
}

Lebanon.java
public class Lebanon extends Country {
@Override
public void language() {
System.out.println("Arabic");
}
}

2
Spain.java
public class Spain extends Country {
@Override
public void language() {
System.out.println("Spanish");
}
}

Main.java
public class Main {
public static void main(String[] args) {
Australia au = new Australia(); English
Lebanon lb = new Lebanon(); Arabic
Spanish
Spain sp = new Spain();
au.language();
lb.language();
sp.language();
}
}

3
Example : Find the output?
class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal { Animals can move


public void move() { Dogs can walk and run
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
In the above example, you can see that even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time, the check is made on the
reference type. However, in the runtime, JVM figures out the object type and would run the
method that belongs to that particular object.

Therefore, in the above example, the program will compile properly since Animal class has the
method move. Then, at the runtime, it runs the method specific for that object.

4
Example: what is the output?
class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal { TestDog.java:26: error: cannot find symbol


public void move() { b.bark();
System.out.println("Dogs can walk and run"); ^
} symbol: method bark()
public void bark() { location: variable b of type Animal
System.out.println("Dogs can bark"); 1 error
}
}
public class TestDog {

public static void main(String args[]) {


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
b.bark();
}
}
Compile time error

*****This program will throw a compile time error since b's reference type Animal doesn't
have a method by the name of bark.

5
Rules for Method Overriding:
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
• The access level cannot be more restrictive than the overridden method's access
level. For example: If the superclass method is declared public then the overridding
method in the sub class cannot be either private or protected.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited, then it cannot be overridden.
• A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
• A subclass in a different package can only override the non-final methods declared
public or protected.
• Constructors cannot be overridden.

6
Java – Overloading:

Overloading: means defining more than one function or constructor, with the same name, but
different in the number or type of parameters.

The idea of overloading is to prepare several functions with the same name. These functions are
similar in terms of function, but slightly different in performance.

In effect, each function contains additional features than the function you created before it.

7
Overloading Conditions:
• Overloading applies only to functions and constructors.
• They must have the same name.
• They must differ in type or number of parameters.
• The return type is not important, the compiler cannot differentiate between functions if
they have different return types.

Interface in Java:
An interface in Java is a blueprint of a class. It has 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 method body. It is used to achieve abstraction and multiple inheritance
in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

The things that can be defined inside the interface:


- Abstract functions do not have an Abstract Method, that is, they do not have a
body.
- functions, but their type is static.
- Variables given their value directly when defining them. Because any variable you
define inside the interface is automatically defined as public final static.
- Nested Classes, that is, a class of type static inside a class of type static.
- Nested Interfaces, that is, an interface within an interface

How to define an interface


An interface is basically Full Abstract, but you should not put the word abstract when defining
it. You cannot define an interface as private or protected because it is always considered public
even if you do not put the word public before it. You also cannot define an interface as final or
static because the interface is designed to make any class that inherits from it override the
functions in it.

So to define an interface, write interface and give it any name you want

8
In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.

Ex.
interface MyInterface {

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

9
Conditions for linking between a class and an interface:
• An object cannot be created from an interface.
• A class can inherit from one class, i.e. it can extend one class.
• A class cannot inherit from an interface, i.e. it cannot extend an interface.
• A class can implement one or more interfaces, i.e. it can implement one or more
interfaces.
• A class that implements an interface must override all functions that it inherits from this
interface.
• An interface can inherit from one or more interfaces. i.e. the interface can implement
extends for one or more interfaces.

Example:

In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.

interface printable{
void print();
}
class A6 implements printable{ Hello
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

10
Interface Example: Drawable

File: TestInterface1.java

//Interface declaration: by first user


interface Drawable{
void draw();
} drawing circle
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario,object is provided by method e.g. getDrawable()
d.draw();
}
}
Interface Example: Bank

File: TestInterface2.java

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
} ROI: 9.15
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();

11
System.out.println("ROI: "+b.rateOfInterest()) ;
}
}

Multiple inheritance in Java by interface:


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.

Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{ Hello
public void print(){System.out.println("Hello");} Welcome
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}

12
Interface inheritance:
A class implements an interface, but one interface extends another interface.

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{ Hello
public void print(){System.out.println("Hello");}
Welcome
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Nested Interface in Java
Note: An interface can have another interface which is known as a nested interface. For example:

interface printable{
void print();
interface MessagePrintable{
void msg();
}
}

13
Abstraction:
Abstraction is the concept of hiding the internal details and describing things in simple terms.
For example, a method that adds two integers. The internal processing of the method is hidden
from the outer world. There are many ways to achieve abstraction in object-oriented
programming, such as encapsulation and inheritance. A Java program is also a great example of
abstraction. Here java takes care of converting simple statements to machine language and hides
the inner implementation details from the outer world.

There are two types of abstraction:

1. Data Abstraction
2. Process Abstraction

Data Abstraction:
When the object data is not visible to the
outer world, it creates data abstraction. If
needed, access to the Objects’ data is
provided through some methods.

Process Abstraction
We don’t need to provide details
about all the functions of an object.
When we hide the internal
implementation of the different
functions involved in a user
operation, it creates process
abstraction.

14
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non- Interface has only static and final variables.
static variables.

4) Abstract class can provide the implementation of interface. Interface can't provide the implementation
of abstract class.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.

6) An abstract class can extend another Java class and An interface can extend another Java
implement multiple Java interfaces. interface only.

7) An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".

8) A Java abstract class can have class members like private, Members of a Java interface are public by
protected, etc. default.

9) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

15
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods


interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}

//Creating subclass of abstract class, now we need to provide the implementation of rest of th
e methods
class M extends B{
public void a(){System.out.println("I am a");} I am a
public void b(){System.out.println("I am b");} I am b
public void d(){System.out.println("I am d");} I am C
I am d
}
//Creating a test class that calls the methods of A interface
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}

16
Polymorphism:
• What is Polymorphism in Java?

Polymorphism in Java is a concept that allows objects of different classes to be treated as if they
belong to a common superclass. This means that a single method name or operator can be used
to perform different operations on different objects. In Java, polymorphism is achieved through
inheritance, where a subclass can inherit methods and attributes from a superclass and also
override or add new methods and attributes.

• What are the types of Polymorphism in Java?

There are two types of polymorphism in Java:

- dynamic polymorphism

- compile-time polymorphism.

• What is Dynamic Polymorphism in Java?

Dynamic polymorphism, also known as runtime polymorphism, is a type of polymorphism in


which the method call is resolved at runtime, based on the actual type of the object that is being
referred to. It occurs when a subclass overrides a method of its superclass. Dynamic
polymorphism is achieved using the method overriding technique.

• What is Compile-time Polymorphism in Java?

Compile-time polymorphism, also known as static polymorphism, is a type of polymorphism in


which the method call is resolved at compile time, based on the method signature. It occurs
when a class has multiple methods with the same name but different parameters. Compile-time
polymorphism is achieved using the method overloading technique.

17
For example, we can have a class as below.

public class Circle {


public void draw(){
System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
}
public void draw(int diameter){
System.out.println("Drwaing circle with default color Black and diameter"+diameter+" cm.");
}
public void draw(int diameter, String color){
System.out.println("Drwaing circle with color"+color+" and diameter"+diameter+" cm.");
}
}

Here we have multiple draw methods but they have different behavior. This is a case of method
overloading because all the methods name is same and arguments are different. Here compiler
will be able to identify the method to invoke at compile-time, hence it’s called compile-time
polymorphism.

Runtime polymorphism is implemented when we have an “IS-A” relationship between


objects. This is also called a method overriding because the subclass has to override the
superclass method for runtime polymorphism. If we are working in terms of the superclass, the
actual implementation class is decided at runtime. The compiler is not able to decide which
class method will be invoked. This decision is done at runtime, hence the name as runtime
polymorphism or dynamic method dispatch.

In other words, Runtime polymorphism or Dynamic Method Dispatch is a process in which


a call to an overridden method is resolved at runtime rather than compile-time.

18
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

class Bike{
void run(){System.out.println("running");}
} running safely with 60km.
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

19

You might also like