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

JAVA Unit-4

The document provides an overview of inheritance in Java, detailing its types, such as single, multilevel, and multiple inheritance, along with concepts like method overriding and the use of interfaces. It explains the parent-child relationship in classes, the role of constructors, and the importance of reusability in object-oriented programming. Additionally, it discusses the limitations of inheritance in Java, including the prohibition of multiple inheritance through classes and the diamond problem.

Uploaded by

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

JAVA Unit-4

The document provides an overview of inheritance in Java, detailing its types, such as single, multilevel, and multiple inheritance, along with concepts like method overriding and the use of interfaces. It explains the parent-child relationship in classes, the role of constructors, and the importance of reusability in object-oriented programming. Additionally, it discusses the limitations of inheritance in Java, including the prohibition of multiple inheritance through classes and the diamond problem.

Uploaded by

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

Unit-4 Inheritance in

Object Oriented design


Types of inheritance, method overriding, abstraction-abstract class,
abstract method, Introduction to interfaces, implementing interface,
keywords-super, final. JS3 pages.
Inheritance in Java
• Inheritance is a powerful object-oriented programming feature offered
by Java.
• Def: Inheritance is a technique of organizing information in a hierarchical
form. This powerful feature allows to one class to inherit the properties
and behaviors of another class.
• Java Inheritance provides a reusability mechanism in object-oriented
programming for the programmers to reuse the existing code within the
new applications. Thereby, the programmer can reduce the code
duplication.
• It does this by allowing the programmer to build a relationship between a
new class and an existing class and define a new code in terms of existing
code. This relationship is known as parent-child relationship in Java.
Inheritance Real-time Example

• In the real world, a child inherits the


features of its parents such as beauty
of mother and intelligence of father as
shown in the below figure.
• It is implemented in Java through
keywords extends (for class
inheritance) and implements (for
interface implementation).
• All the classes extends java.lang.object
by default. This means Object is the
root class of all the classes in Java.
Therefore, by default, every class is the
subclass of java.lang.object.
Example
inheritance relationship. They are as follows:

 Vehicle is the parent class (superclass) of Car.


 Car is the child class (subclass) of Vehicle.
 Car is the parent class of Alto.
 Alto is the child class of Vehicle.
 Car inherits from Vehicle.
 Alto inherits from both Vehicle and Car.
 Alto is derived from Car.
 Car is derived from Vehicle.
 Alto is derived from Vehicle.
 Alto is a subtype of both Vehicle and Car.
Terminology
1. Superclass/Parent class: The class from where a subclass inherits
features is called superclass. It is also called base class or parent
class in java.
2. Subclass/Child class: A class that inherits all the members (fields,
methods, and nested classes) from another class is called subclass.
It is also called a derived class, child class, or extended class.
3. Re-usability: A mechanism that facilitates to reuse fields and
methods of the existing class into the new class is known as
reusability. When you create a new class, you can use the same
fields and methods already defined in the previous class. This is
called reusability.
Syntax to Create Subclass

• A subclass can be created by using “extends” keyword.


• The general syntax for defining and extending a class is as follows:

accessModifier class subclassName extends superclassName


{
// Variables of subclass
// Methods of subclass
}
• In the above syntax, we have created a subclass class that inherits from
another class by extend clause in the class header. Here, class and
extends are two keywords.
• The extends keyword indicates that you are deriving a new class (derived
class) from the existing class (base class).
• Inheritance is a compile-time mechanism. A parent class can have any
number of derived class but a derived can have only one parent class.
Features of Superclass are Inherited in Subclass

// Creating a superclass.
public class BaseClass { public class InheritanceTest {
void features() public static void main(String[] args)
{
{ // Create an object of the derived class.
System.out.println("Feature A"); DerivedClass d = new DerivedClass();
System.out.println("Feature B");
// Call features() method from the derived class using object
} } reference variable d.
// Creating a subclass. d.features();
public class DerivedClass extends BaseClass {
// Call ownFeature() method using reference variable d.
void ownFeature() d.ownFeature();
{ }
}
System.out.println("Feature C");
}
}
Inheritable Members of Why do We Use
Classes
Inheritance in Java?
Types of Fields/Members Classes
• We can reuse the code from the base class.
Instance variables Yes • we can increase features of class or method by overriding.
Static variables Yes • Inheritance is used to use the existing features of class.
Abstract methods Yes
• It is used to achieve runtime polymorphism i.e method
overriding.
Instance methods Yes
• Using inheritance, we can organize the information in a
Static methods Yes
hierarchal form.
Constructor No

Initialization blocks No
Role of Constructor in Java
Inheritance
• The role of constructor in inheritance is that the constructor in the
superclass is responsible for building an object of superclass and the
constructor of subclass builds an object of subclass.

• When the constructor of a subclass is called during the object creation,


by default, it calls the default constructor of superclass.
• The superclass constructor can be called using keyword “super” from
the subclass constructor. It must be the first statement in a constructor.

• We can call other constructors of same class using this keyword, but
you cannot call a subclass constructor from the superclass constructor.
Important Rules of Java
Inheritance
1. We cannot assign a superclass to the subclass.
2. We cannot extend the final class.
3. A class cannot extend itself.
4. One class can extend only a single class.
5. We cannot extend a class having a private constructor, but if we have private
constructor as well as public constructor, then we can extend superclass to subclass. In
this case, the only public constructor will work.
6. If we assign subclass reference to superclass reference, it is called dynamic method
dispatch in java.
7. Constructor, Static initialization block (SIB), and Instance initialization block (IIB) of the
superclass cannot be inherited to its subclass, but they are executed while creating an
object of the subclass.
8. A static method of superclass is inherited to the subclass as a static member and non-
static method is inherited as a non-static member only.
Superclass and Subclass Examples
public class Parentclass { public class Parentclass {
void m1() { void m1()
{
System.out.println("Superclass m1 method");
System.out.println("Superclass m1 method");
} } } }
public class Childclass extends Parentclass { public class Childclass extends Parentclass {
void m2() { void m2()
{
System.out.println("Childclass m2 method"); System.out.println("Childclass m2 method");
} } } }
public class Test { public class Test {
public static void main(String[] args)
public static void main(String[] args) {
{
// Creating an object of superclass. // Creating an object of subclass.
Parentclass p = new Parentclass(); Childclass c = new Childclass();
p.m1();
// Accessing superclass and subclass members using subclass
// Here, subclass members are not available to superclass. object reference variable.
// So, we cannot access them using superclass reference variable. c.m1();
c.m2();
} }
} }
// Subclass inheriting from Vehicle class.
// Base class
class Bicycle extends Vehicle
class Vehicle { {
String brand; Bicycle(String brand) {
super(brand);
Vehicle(String brand) {
}
this.brand = brand; } void pedal() {
void honk() { System.out.println("Pedaling the " + brand + " bicycle");
}}
System.out.println("Honk honk!");
}}
// Subclass inheriting from Vehicle class. public class Main {
public static void main(String[] args) {
class Car extends Vehicle { Car myCar = new Car("Toyota", "Corolla");
String model; Bicycle myBicycle = new Bicycle("Schwinn");
myCar.drive();
Car(String brand, String model) {
myCar.honk();
super(brand); System.out.println();
this.model = model; } myBicycle.pedal();
myBicycle.honk();
void drive() {
} }
System.out.println("Driving the " + brand + " " + model);
} }
Base class and Derived class Members with Same Name
how to access superclass members from the subclass?
public class Number { Answer with Super keyword
int x = 20; public class Number {
void display() { int x = 20;
System.out.println("X = " +x); Method void display() {
} } override System.out.println("X = " +x);
} }
public class Number2 extends Number {
public class Number2 extends Number {
int x = 50;
int x = 50;
void display() { void display() {
System.out.println("X = " +x); System.out.println("X = " +super.x);
}} System.out.println("X = " +x);
public class NumberTest { }}
public static void main(String[] args) public class NumberTest {
public static void main(String[] args)
{
{
// Creating an instance of subclass.
// Creating an instance of subclass.
Number2 n = new Number2(); Number2 n = new Number2();
n.display(); n.display();
}} }}
Types of Inheritance in Java
Based on class, there are three types of inheritance in Java.
They are as follows:
1. Simple/Single level Inheritance
2. Multiple Inheritance
3. Hybrid Inheritance

Note: multiple inheritance and hybrid inheritance are supported through the
interface only.
Single level public class A {
// Declare an instance method.
public void methodA() {
Inheritance System.out.println("Base class method");
} }
• A class is extended by only one class, it is
called single-level inheritance in Java or // Declare a derived class or subclass and extends class A.
simply single inheritance. public class B extends A {
public void methodB()
{
System.out.println("Child class method");
} }

public class Myclass {


public static void main(String[] args)
{
// Create an object of class B.
B obj = new B();
obj.methodA();
// methodA() of B will be called because by default, it is
available in B.
obj.methodB();
// methodB() of B will be called.
} }
Multilevel Inheritance in Java public class X {
public void methodX() {
System.out.println("Class X method"); }
• A class that is extended by a }
class and that class is extended
public class Y extends X {
by another class forming chain public void methodY() {
inheritance is called multilevel System.out.println("Class Y method"); }
inheritance in Java. }

public class Z extends Y {


public void methodZ() {
System.out.println("Class Z method"); }

public static void main(String[] args)


{
// Creating an object of class Z.
Z z = new Z();
z.methodX(); // Calling X grand class method.
z.methodY(); // Calling Y parent class method.
z.methodZ(); // Calling Z class local method.
}}
Hierarchical public class A {

Inheritance public void msgA() {


System.out.println("Method of class A"); } }
public class B extends A {
• A class that is inherited by // Empty class B, inherits msgA of parent class A.
many subclasses is known as }
hierarchical inheritance in public class C extends A {
// Empty class C, inherits msgA of parent class A.
Java. }
public class D extends A {
// Empty class D, inherits msgA of parent class A.
}
public class MyClass {
public static void main(String[] args) {
// Create the object of class B, class C, and class D.
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();

// Calling inherited function from the base class.


obj1.msgA();
obj2.msgA();
obj3.msgA(); } }
Multiple
Inheritance
• Deriving subclasses from more
than one superclass is known
as multiple inheritance in Java.

Practically, it is very rare and difficult to use in a software


project because it creates ambiguity, complexity, and confusion
when a class inherits methods from two superclasses with the
same method signature.
The ambiguity created by the multiple inheritance is called
diamond problem in Java.

Now, you need to understand why Java does not support multiple
inheritance through class.
Why Java does not Support Multiple Inheritance
through Classes?
class A {
void msg()
{
System.out.println("Hello Java");
}}

class B {
void msg()
{
System.out.println("Welcome you");
} }

class C extends A, B { // Suppose if it is.


public static void main(String args[])
{
// Creating an instance of class C.
C obj = new C();
obj.msg(); // Now which msg() method would be
called?
}}
How does Multiple Inheritance implement in Java?
• Multiple inheritance can be implemented in Java by using interfaces.
• A class cannot extend more than one class but a class can implement
more than one interface.
public interface Printable
{ // Class A implementing multiple interfaces.
// Declare an abstract method. Methods in an public class A implements Printable, Showable
interface are public and abstract by default. So, it {
is not mandatory to write abstract keyword. // The concrete class which implements an interface must
// Abstract method must not have a body. implement the abstract method declared in the interface.
void print(); // no body. public void print() { System.out.println("Hello Java"); }
} public void show() { System.out.println(" Welcome you"); }

public interface Showable public static void main(String[] args) {


{ // Create an object of class A and call print() and show() methods
void show(); // No body. using object reference variable obj.
} A obj = new A();
obj.print();
obj.show(); } }
Hybrid
Inheritance
• A hybrid inheritance in Java is a combination of single and multiple
inheritance.
• It can be achieved in the same way as multiple inheritance using interfaces
in Java.
Method Overriding in public class MyTest extends Childclass {
Inheritance public static void main(String[] args) {
Childclass obj = new Childclass();
public class Baseclass { System.out.println("Value of x: " +obj.x);
int x = 20; System.out.println("Value of y: " +obj.y);
// x of class Childclass is called.
// Overridden method. obj.msg(); // msg() of Childclass is called.
void msg() { obj.msg2(); // msg2() of Childclass is called.
System.out.println("Base class method"); Baseclass obj2 = new Childclass();
System.out.println("Value of x: " +obj2.x);
} } // x of Baseclass is called.
public class Childclass extends Baseclass { // System.out.println("Value of y: " +obj2.y);
// Error because y does not exist in Baseclass.
int x = 50;
obj2.msg(); // msg() of Childclass is called.
int y = 100; // obj2.msg2(); // Error because the method msg2() does not
// Overriding method. exist in Baseclass. } }
Output:
void msg() { Value of x: 50
System.out.println("Child class first method"); } Value of y: 100
Child class first method
void msg2() { Child class second method
System.out.println("Child class second Value of x: 20
method"); } } Child class first method
public class Hello { public class Hi extends Hello {
Hi()
// Declare an instance block.
{
{ System.out.println("Hi constructor");
show(); }
// Override the show() method.
} void show()
Output:
Hello() {
Hi method
{ System.out.println("Hi method");
Hello constructor
}
System.out.println("Hello constructor"); Hi method
}
Hi constructor
show();
Hi method
public class TestHelloHi extends Hi {
} Hi method
public static void main(String[] args) {
void show() Hello constructor
Hi obj = new Hi();
Hi method
{ obj.show(); // show() method of Hi class is called.
Hi constructor
System.out.println("Hello method"); overrride Hi method
// Superclass reference is equal to child class object.
Hello obj1 = new Hi();
} obj1.show();
} } }
Method Overloaded
public class Animal {
void food() {
System.out.println("What kind of food do lions eat?"); }
}
public class Lion extends Animal {
void food(int x) {
System.out.println("Lions eat flesh"); } Method overloading
}
public class LionTest extends Lion {
public static void main(String[] args) {
Animal a = new Lion();
a.food(); // food() method of class Animal is called.
// a.food(20); // Compile time error.

Lion l = new Lion();


l.food(); // food() method of class Lion is called.
l.food(10); // food() method of class Lion is called.
} }
Super Keyword to call constructor

• Super keyword in Java is a reference variable that refers to an immediate superclass object.

public class P public class Q extends P


{ {
P() Q() {
{ // super(); automatically added by Java compiler at compile-
// Invisible super(); present here. time.
System.out.println("P class's no-arg constructor"); System.out.println("Q class's no-arg constructor");
} } }
P(int x)
{ public class Test {
System.out.println("P class's one argument public static void main(String[] args)
constructor"); {
} // Create an object of class Q and call the method show()
public void show() using reference variable obj.
{ Q obj = new Q();
System.out.println("P class's method"); obj.show();
} }
} }
Call Superclass Method
public class Student {
// Overridden method.
void displayInfo() { System.out.println("I am Srikanth"); }
}
public class School extends Student {
// Overriding method.
void displayInfo() { System.out.println("My college 's name is NMIMS"); }
void msg() {
super.displayInfo(); // displayInfo of class Student is called.
displayInfo(); // displayInfo of class School is called. }
public static void main(String[] args) {
// Create an instance of subclass School.
School sc = new School();
sc.msg();
} }
This keyword
public class ABC {
// Declare a default constructor.
ABC() { System.out.println("HELLO SRIKANTH"); }
// Declare a parameterized constructor with parameter x. x is a local variable.
ABC(int x) {
// This statement calls default constructor from parameterized constructor.
this(); // Must be the first line in the constructor.
System.out.println("WELCOME INDIA");
}
}
public class ABCTest {
public static void main(String[] args) {
// Create an object of class ABC and pass the value to parameterized constructor.
ABC obj = new ABC(12);
}
}
Passing this keyword as Argument to Method call

public class Test {


// Declare an instance method whose a parameter is t with class type Test.
void m1(Test t) { System.out.println("m1 method is called"); }

void m2() {
m1(this);
// Passing this as an argument in the m1 method. this keyword will pass the reference of current class
object to the m1 method.
}

public static void main(String[] args)


{
Test t = new Test();
t.m2(); // m2 method is called.
}
}
Abstraction in Java

• Abstraction in Java is Let’s first take ATM machine as a real-time example.


We all use an ATM machine for cash withdrawal,
another OOPs principle that provides a money transfer, retrieve min-statement, etc. in our
powerful way to manage complexity. daily life.
But we don’t know internally what things are
• The process of hiding complex internal happening inside ATM machine when you insert an
implementation details from users and ATM card for performing any kind of operation.

providing only necessary functionality


is called abstraction.
• The main purpose of abstraction is to
represent the essential features
without including the background
details. Let’s take some real-time
examples to understand the concept
of abstraction in simple words.
How to Achieve Abstraction in
Java?
• There are two ways to achieve or implement abstraction in Java program.
They are as follows:
• Abstract class (0 to 100%)
• Interface (100%)

• Java allows us to implement multiple levels of abstraction for a Java


project. Abstract class and interface are the most common ways to
achieve abstraction in Java. Let’s understand each way and learn how to
implement it in Java program.
Abstract Class in Java
• An abstract class in Java is a class, which is declared with an abstract
keyword. It is just like a normal class but has two differences.
1. We cannot create an object of this class. Only objects of its non-
abstract (or concrete) sub-classes can be created.
2. It can have zero or more abstract methods which are not allowed in a
non-abstract class (concrete class). Class loader class is a good example
of an abstract class that does not have any abstract methods.
When to Use Abstract class in Java?
An abstract class can be used when we need to share the same method
to all non-abstract subclasses with their own specific implementations.
Abstract Method in Java
• A method that is declared with abstract modifier in an abstract class
and has no implementation (means no body) is called abstract
method in Java. It does not contain any body.
• Syntax:
• abstract type methodName(arguments); // No body

• For example:
• abstract void msg(); // No body.
public abstract class MyTest {
public class MyClass {
abstract void calculate(int a, int b); // No body. public static void main(String[] args)
} {
public class Addition extends MyTest { // Creating objects of classes.
Addition a = new Addition();
void calculate(int a, int b) { Subtraction s = new Subtraction();
int x = a + b; Multiplication m = new Multiplication();
// Calling methods by passing argument values.
System.out.println(“Sum: ” +x); } a.calculate(20, 30);
} s.calculate(10, 5);
public class Subtraction extends MyTest { m.calculate(10, 20); }
}
void calculate(int a, int b) {
int y = a - b;
System.out.println(“Subtract: ” +y); }
}
public class Multiplication extends MyTest {
void calculate(int a, int b) {
int z = a * b;
System.out.println(“Multiply: ” +z); }
}
Features of Abstract class in
Java
• There are following important features of abstract class in Java that you should
keep in mind. They are as follows:
1. Abstract class is not a pure abstraction in Java.
2. In Java, object creation is not possible for an abstract class because it is a
partially implemented class, not fully implemented class.
3. It can be abstract even with no abstract method.
4. It can have one or more abstract methods or non-abstract methods (or concrete
methods) or a combination of both methods.
5. Abstract class allows to define private, final, static and concrete methods.
Everything is possible to define in an abstract class as per application requirements.
6. It can have constructors.
7. Abstract class does not support multiple inheritance in Java but allows in
interfaces.
8. It can implement one or more interfaces in Java.
public abstract class Hello {
public abstract class Employee {
// Declaration of instance method. private String name;
public void msg1() { private int id;
public Employee(String name, int id) {
System.out.println("msg1-Hello"); } this.name = name;
abstract public void msg2(); // abstract method. this.id = id; }
} // Declaration of concrete method.
void m1() {
public class Test extends Hello { System.out.println("Name: " +name);
// Overriding abstract method. System.out.println("Id: " +id); }
}
public void msg2() {
public class Engineer extends Employee {
System.out.println("msg2-Test"); } public Engineer(String name, int id) {
public static void main(String[] args) { super(name, id); // This statement is used to call super class
constructor.
// Creating object of subclass Test.
}
Test obj = new Test(); public static void main(String[] args) {
obj.msg1(); // Creating an object of the subclass of abstract class.
Engineer e = new Engineer(“Sri", 4000);
obj.msg2(); } e.m1();
} } }
public abstract class Identity {
public class Mainclass
abstract void getName(String name);
{
abstract void getGender(String gender); public static void main(String[] args)
abstract void getCity(String city); {
}
// Declaring abstract class reference equal to subclass
public class Person extends Identity object.
{
void getName(String name) Identity i = new Person();
i.getName(“SRI");
{ System.out.println("Name : " +name); }
i.getGender("MALE");
void getGender(String gender) i.getCity(“Shirpur");
{ System.out.println("Gender : " +gender); }
void getCity(String city) // This statement will generate a compile-time error
because
{ System.out.println("City: " +city); }
// we cannot access newly added method in subclass using
superclass reference.
// Newly added method in subclass. // i.getCountry("INDIA");
void getCountry(String country) }
}
{ System.out.println("Country: " +country); }
}
Interface in Java

• An interface in Java is syntactically similar to a class


but can have only abstract methods declaration and
constants as members.
• Every interface in Java is abstract by default. So, it is
not compulsory to write abstract keyword with an
interface.
• Once an interface is defined, we can create any
number of separate classes and can provide their own
implementation for all the abstract methods defined
by an interface.
• A class that implements an interface is
Syntax:
called implementation class. A class can implement accessModifier interface interfaceName
any number of interfaces in Java. Every {
implementation class can have its own // declare constant fields.
implementation for abstract methods specified in the // declare methods that abstract by
interface as shown in the below figure. default.
}
Various forms of interfaces
public interface ConstantValues {
public class Sub implements ConstantValues
// Declaration of interface variables. {
int x = 20; void sub()
{
int y = 30; }
int p = y - x;
public class Add implements ConstantValues System.out.println("Sub: " +p);
{ }
}
int a = x;
public class Test
int b = y; {
void m1() { public static void main(String[] args)
{
System.out.println("Value of a: " +a); Add a = new Add();
System.out.println("Value of b: " +b); } a.m1();
void sum() { a.sum();
Sub s = new Sub();
int s = x + y; s.sub();
System.out.println("Sum: " +s); } }
}
}
Polymorphism in Java Interface

public interface Rectangle { public class Execution


void calc(int l, int b); // no body. } {
public static void main(String[] args)
public class RecArea implements Rectangle { {
public void calc(int l, int b) { Rectangle rc; // Creating an interface reference.
int area = l * b; // Implementation. rc = new RecArea(); // Creating object of RecArea.
rc.calc(20, 30); // calling method.
System.out.println("Area of rectangle = "+area); }
} rc = new RecPer(); // Creating an object of RecPer.
rc.calc(20, 30);
}
public class RecPer implements Rectangle }
{
public void calc(int l, int b) {
int perimeter = 2 * (l + b); // Implementation.
System.out.println("Perimeter of rectangle =
"+perimeter); }
}
Multiple Inheritance in Java by
Interface
• When a class implements more than one interface, or an interface
extends more than one interface, it is called multiple inheritance.
Various forms of multiple inheritance are shown in the following
figure.
interface Home { void homeLoan(); }
interface Car { void carLoan(); }
interface Education { void educationLoan(); }
public class Multi implements Home, Car, Education {
public void homeLoan() { System.out.println("Rate of interest on home loan is 8.5%"); }
public void carLoan() { System.out.println("Rate of interest on car loan is 9.25%"); }
public void educationLoan() { System.out.println("Rate of interest on education loan is 10.45%"); }

public static void main(String[] args) {


// TODO Auto-generated method stub
Multi l = new Multi();
l.homeLoan();
l.carLoan();
l.educationLoan();
}
}
Nested interfaces
interface Outer { public class Test {
void m1(); public static void main(String[] args) {
interface Inner // Creating an object of class MyClass1.
{ void m2(); } MyClass1 c1 = new MyClass1();
} c1.m1(); // Calling m1() method.
// Implementation of top-level interface:
class MyClass1 implements Outer // Creating an object of class MyClass2.
{
MyClass2 c2 = new MyClass2();
c2.m2(); // Calling m2() method.
public void m1() { System.out.println("Hello"); }
}
}
}

// Implementation of inner interface:

class MyClass2 implements Outer.Inner


{
public void m2() { System.out.println("Shirpur");
}
}
Interface inside Class

class VehicleTypes {
interface Vehicle { public int getNoOfWheels(); }
}
class Bus implements VehicleTypes.Vehicle { public int getNoOfWheels() { return 6; } }
class Car implements VehicleTypes.Vehicle { public int getNoOfWheels() { return 4; } }
class Bike implements VehicleTypes.Vehicle { public int getNoOfWheels() { return 2; } }
public class VehicleTest {
public static void main(String[] args) {
Bus b = new Bus();
System.out.println(b.getNoOfWheels());

Car c = new Car();


System.out.println(c.getNoOfWheels());

Bike bk = new Bike();


System.out.println(bk.getNoOfWheels()); } }
Difference between Abstract Class and Interface in Java
Abstract class Interface
Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
An abstract class can extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.
An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
Example: Example:
public abstract class Shape { public interface Drawable {
void draw();
public abstract void draw(); }

}
Difference between Class and
Interface in Java
CLASS INTERFACE
The ‘class’ keyword is used to create a class. The ‘interface’ keyword is used to create an interface.

An object of a class can be created. An object of an interface cannot be created.


Class doesn’t support multiple inheritance. Interface supports multiple inheritance.
A class can inherit another class. An Interface cannot inherit a class.
A class can be inherited by another class using the An Interface can be inherited by a class using the keyword
keyword ‘extends’. ‘implements’ and it can be inherited by another interface using
the keyword ‘extends’.
A class can contain constructors. An Interface cannot contain constructors.
It cannot contain abstract methods. It consists of abstract methods only.
Variables and methods can be declared using any Variables and methods are declared as public only.
specifiers like public, protected, default, private.
Interface Static Method
• A static method within an interface is explicitly defined with a static keyword and method body.

public interface Perimeter {


void msg();
static int peri(int l, int b) { return 2*(l + b); }
}
public class Rectangle implements Perimeter {
public void msg() { System.out.println("Perimeter of rectangle"); }
public static void main(String[] args) {
Perimeter p = new Rectangle();
p.msg();
int perimeter = Perimeter.peri(20,30);
System.out.println(perimeter); }
}
public interface A {
static void m1() { System.out.println("Static method in A"); }
}
public interface B {
static void m1() { System.out.println("Static method in B "); }
}
public class AB implements A, B{
public static void main(String[] args)
{
A.m1(); // Calling static method of interface A.
B.m1(); // Calling static method of interface B.
}
}
Real-time example for
polymorphism
Final Keyword in Java |
The final keyword declared with variable, method, and class indicates
that “This cannot be modified”.
• The value of the final variable cannot be changed.
• A final method cannot be overridden.
• A final class cannot be inherited.
Final Variable in Java
public class FinalVariableEx {
// Declare a final instance variable. public static void main(String[] args)
final int a = 20; {
// Create an object of the class.
// Declare an instance method. FinalVariableEx fv = new FinalVariableEx();
void change() {
// Change the value of the final instance variable. // Call change() method using reference variable fv.
fv.change();
a = 40; // compile time error. A final variable's value cannot be
changed. }
System.out.println(a); }
// Declare a final local variable inside the method.
final int i = 0;
for(i=0; i< 5; i++) // compile time error.
{
System.out.println("Value of I: " +i);
}
}
Final Method
public class FinalMethodEx {
public static void main(String[] args)
FinalMethodEx() {
{ // Create an object of FinalMethodEx class.
System.out.println("This is a default constructor"); FinalMethodEx fm = new FinalMethodEx();
}
// Call final method using reference variable fm.
final int a = 50; fm.show();
final void show() { }
System.out.println("Value of a: " +a); }
}
}
public class FinalMethodExTest extends FinalMethodEx {
void show() {
// Compile time error because we cannot override the
final method from FinalMethodEx.
System.out.println("This is the final method of
FinalMethodEx class");
}
Final Class
public final class AB {
void show() {
System.out.println("Final class cannot be inherited"); }
}

public class ABTest extends AB {


// Here compile-time error because the final class cannot be extended.
public static void main(String[] args) {
// Create the object of class AB.
AB ab = new AB();
ab.show(); // Calling show() method using object reference variable ab.
}
}

You might also like