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

Java Chapter 4 (3)

Chapter 4 covers key Object-Oriented Programming (OOP) concepts including encapsulation, inheritance, polymorphism, method overloading, and overriding, as well as abstract classes and interfaces. The chapter explains how these principles help reduce complexity, increase reusability, and improve code maintainability. It also discusses the benefits of encapsulation, the rules of method overriding, and the distinction between compile-time and runtime polymorphism.

Uploaded by

gemechisgadisa77
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)
2 views

Java Chapter 4 (3)

Chapter 4 covers key Object-Oriented Programming (OOP) concepts including encapsulation, inheritance, polymorphism, method overloading, and overriding, as well as abstract classes and interfaces. The chapter explains how these principles help reduce complexity, increase reusability, and improve code maintainability. It also discusses the benefits of encapsulation, the rules of method overriding, and the distinction between compile-time and runtime polymorphism.

Uploaded by

gemechisgadisa77
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/ 63

Chapter 4

OOP Concepts
Objective

After completing this chapter you will be able to:

 Understand 4 pillars of OOP

 Encapsulation

 Inheritance, Method overloading and overriding

 Polymorphism

 Abstract classes and Interfaces


Main OOP Concepts:

• Other concepts:

 Method overloading and

 Method overriding

 Accessing Superclass
Members

 Abstract classes and

 Interfaces
General objective of OOP concept

 Using encapsulation we group fields and methods, and in this way we


reduce complexity.

 Increase reusability of objects. Also objects create other objects and


“send messages” to each other (in Java, call each other’s methods).

 With abstraction we hide the details and complexity and show only the
essentials. Again this technique also reduce complexity and isolate the
impact of changes in the code (easier program maintenance).

 With inheritance we eliminate redundant code.

 With polymorphism we refactor ugly switch/case statements.

 Easier GUI programming.


What is Encapsulation ?
• Encapsulation is one of the four fundamental OOP concepts.

• Encapsulation is the way of declaring the data members as private and


providing access to the data members through public methods (getter and
setter methods).

• In other ways, Encapsulation is a mechanism of wrapping the data


(variables) and code acting on the data (methods) together as a single unit.

• As private field can’t be access outside the class, and variables of a class will
be hidden and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding. (Abstraction in action)

• So, to achieve encapsulation in Java −

– Declare the variables of a class as private.

– Provide public setter and getter methods to modify and view the variables.
Why need Encapsulation?
• Combining data and how it's manipulated in one place :
– This is achieved through the state (the private fields) and the
behaviours (the public methods) of an object.
• Only allowing the state of an object to be accessed and modified
through behaviours:
– The values contained within an object's state can then be strictly
controlled.

• Hiding the details of how the object works:


– The only part of the object that is accessible to the outside world is its
behaviours. What happens inside those behaviours and how the state
is stored is hidden from view.
• Can safely modified the implementation without worrying breaking the existing
code that uses the class
• Keeps class tidy(marking by order) by keeping the visible fields to a minimum
• Easier to use and understand
Benefits of having Encapsulation
 By providing only a setter or getter method, the fields of a class can be
made read-only or write-only.
 Control over the data:
 It is achieved using class and access modifier private, protected,
public.
 Suppose you want to set the value of id which should be greater than
100 only, you can write the logic inside the setter method.
 You can write the logic not to store the negative numbers in the setter
methods.
 The users of a class do not know how the class stores its data.
 A class can change the data type of a fields, and a users of the class
do not need to change any of their code.
Exercise: Write a simple program of encapsulation that has only one
field with its setter and getter methods.
Java Abstraction
• In OOP, Abstraction is a process of hiding the implementation details
form the user and showing only essential functionality to the user.
• In other words user will have the information on what the object does
instead of how it does it.
• For example, All are performing operations on the ATM machine like
cash withdrawal, money transfer, retrieve mini-statement…etc are
high level implementations. but we can't know internal details about ATM.
• In java Abstraction is achieved using Abstract classes and Interfaces.

• Benefits
– Simpler interface
– Reduce the impact of change
Inheritance
• Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
• It is one of the cornerstones of OOP because it allows the creation of
hierarchical classifications.
• The idea behind inheritance 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 the parent class.
• The class that is inherited is called the parent class, the base class, or
the superclass.
• The class that inherits is called the child class, the derived class, or the
subclass.
• Therefore, a subclass is a specialized version of a superclass:

– It inherits all of the instance variables and a method defined by the


superclass and adds its own (unique elements).
Inheritance …
 Inheritance is best for code reusability.
 Objects can relate to each other with “is a” relationship.
 For example: Solitaire is a type of game; a truck is a type of vehicle; a cat
is a type of animal; an invoice is a type of transaction.

Fig: Class hierarchy

• Syntax:
class SubClass extends SuperClass {
//methods and fields
}
Types of inheritance in java
• On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical consider the figure below.
How Inheritance is work ??
 A superclass’s public members are accessible anywhere in its subclass
types.
 A superclass’s private members are accessible only in methods of that
superclass i.e. they are not accessible in the subclasses.
 private members are generally not inherited.
 A superclass’s protected access members serve as an intermediate level
of protection between public and private access.
 A superclass’s protected members are accessible in the superclass, in
the subclasses and other classes in the same package.
Why multiple inheritances is not supported in java?
 To reduce the complexity and simplify the language, multiple inheritance
is not supported in java.
 Consider a scenario where A, B, and C are three classes.
 The C class inherits A and B classes.
 If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
 Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes.
 So whether you have same method or different, there will be compile time
error.
Method Overloading
 Method overloading is a part of class has multiple methods having
same name but different in parameters.
 Is used to increases the readability of the program, that means, If we
have to perform only one operation, having same name of the methods
increases the readability of the program.
 So, we perform method overloading to figure out the program quickly.
 To call overload methods, it is must to define the type and number of
arguments to determine which version of overload method is be called.
 Return type may or may not be same
 Constructors can also be overloaded.
Method Overloading
 Method Overloading is not possible by changing the return type of
method only.
 Because,
• In java, method overloading is not possible by changing the return
type of the method only because of ambiguity.
• Let's see how ambiguity may occur in next slide.
class Adder{
static int add(int a, int b) Output:
return a + b;
• Compile Time Error:
static double add(int a, int b)
method add(int,int) is
return a + b;
already defined in class
}
Adder
class Main{
public static void main (String[] args) { • Here, how can java
System.out.println(Adder.add(11, 11)); determine which add()
} method should be called?
}
Method Overloading
 Can we overload java main() method?
• Yes, by method overloading.
• You can have any number of main methods in a class by method
overloading.
• But JVM calls main() method which receives string array as
arguments only.
class TestMain{
public static void main (String args) {
System.out.println(“Main method with String”);
}
public static void main (String[] args) {
System.out.println(“Main method with String []”);
}
public static void main () {
System.out.println(Main method without String []”);
}
} Output: main with String[]
Method Overloading and Type Promotion
• One type is promoted to another implicitly if no matching datatype is found.
• Let's understand the concept by the figure given below:

• As displayed in the above diagram, byte can be promoted to short, int,


long, float or double.
• The short datatype can be promoted to int, long, float or double.
• The char datatype can be promoted to int, long,float or double and so on.
Example of Method Overloading with TypePromotion

class OverloadingCalculation1{
void sum (int a, long b) {
System.out.println(a + b);
}
void sum (int a, int b, int c) {
System.out.println(a + b + c);
}
public static void main (String[] args) {
OverloadingCalculation1 obj = new OverloadingCalculation1;
obj.sum(20, 20); //now second int literal will be promoted to long
obj.sum(20, 20, 20);
}
Output: 40
} 60

Note: If there are matching type arguments in the method, type promotion is not
performed.
void sum(int a,int b){}
void sum(long a, long b){}
Method Overloading with TypePromotion Ambiguity

 If there are no matching type arguments in the method, and each method
promotes similar number of arguments, there will be ambiguity.

class OverloadingCalculation1{
void sum (int a, long b) {
System.out.println(a + b);
}
void sum (long a, int b) {
System.out.println(a + b);
}
public static void main (String[] args) {
OverloadingCalculation1 obj = new OverloadingCalculation1;
obj.sum(20, 20); //now ambiguity
}
}

Note: Compile Time Error.


Method Overriding

 In object-oriented terms, overriding means to override the functionality of


an existing method.
 When a class defines a method using the same name, return type, and
arguments as a method in its superclass, the method in the subclass
overrides the method in the superclass.
 When the method is invoked for an object of the subclass, it’s the
subclass definition of the method is called, not the superclass's old
definition.
 In other words, If subclass (child class) has the same method as
declared in the parent class, it is known as method overriding.

 Constructors cannot be overridden.


Method Overriding …

Rules for Method Overriding:

• The class must extend the class that defines the method you want to
override.
• The method must be declared in the base class with public or protected
access. You can’t override a private method.
• If the superclass method is declared public then the overriding method in
the sub class cannot be private or protected.
• The method in the subclass must have the same signature as the
method in the base class. In other words, the name of the method and
the parameter types must be the same.
• A method declared final, static or private cannot be override.
• A method declared static cannot be overridden but can re-declared.
Polymorphism
 Polymorphism is a concept by which we can perform a single action in
different ways.
 Polymorphism is derived from Greek words: poly (many) and morphs
(forms).

 It allows an interface to be used for general class of actions.

 In other term polymorphism refers to:

– The ability of Java to use base class variables to refer to subclass


objects, keep track of which subclass an object belongs to, and use
overridden methods of the subclass.

 There are two types of polymorphism in Java:


• runtime polymorphism. (dynamic polymorphism)
• compile-time polymorphism. (static polymorphism)
Runtime Polymorphism
 We can perform polymorphism in java by method overloading and
method overriding.
 If you overload a method in Java, it is the example of compile time
polymorphism.
 Here, we will focus on runtime polymorphism in java.
 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.
 In this process, an overridden method is called through the reference
variable of a superclass.
 The determination of the method to be called is based on the object being
referred to by the reference variable.
Runtime Polymorphism

class Animal{
public void eat() {
System.out.println(“Animal Eating…”);
}
}
class Dog extends Animal{
public void eat() {
System.out.println(“Dog Eating…”);
}
}

1. Animal animal1 = new Animal(); //D1 on the heap


• Animal1.eat(); // Animal Eating…
2. Animal animal2 = new Dog(); //D2: upcasting
• Animal2.eat(); // Dog Eating…
3. Dog dog = new Animal(); // Invalid

RULES of polymorphism
• Reference variable  Own class Object
• Reference variable  Child class Object //Upcasting
• Reference variable can’t point to Parent class Object
Upcasting
 If the reference variable of Parent class refers to the object of Child class,
it is known as upcasting. For example:

– class A{}

– class B extends A{}

– A a = new B(); //upcasting

• For upcasting, we can use the reference variable of class type or an


interface type.

• For Example: • Here, the relationship of B class would be:

B IS-A A
interface I{}
B IS-A I

class A{} B IS-A Object

• Since Object is the root class of all classes in Java, so we can write B
class B extends A implements I{} IS-A Object.
Example #1: 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.
class Bike{
void run () {
System.out.println(“Running”);
}
}
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();
}
} // Output: Running safely with 60km
Runtime Polymorphism Example 2: Bank
 Consider a scenario where Bank is a class that provides a method to get
the rate of interest.

 However, the rate of interest may differ according to banks. For example,
SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of
interest respectively.
Sample Solution
class Bank {
float getRateOfInterest() { return 0; }
}
class SBI extends Bank{
float getRateOfInterest() { return 8.4f;}
Output
}
class ICICI extends Bank{ SBI Rate of Interest: 8.4
float getRateOfInterest() { return 7.3f;}
ICICI Rate of Interest: 7.3
}
class ICICI extends Bank{ AXIS Rate of Interest: 9.7
float getRateOfInterest() { return 9.7f;}
}
class TestPolymorphism {
public static void main(String args[]) {
Bank b = new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
Runtime Polymorphism with Data Member
 A method is overridden, not the data members, so runtime polymorphism
can't be achieved by data members.
 In the example given below, both the classes have a data member
speedlimit.
 We are accessing the data member by the reference variable of Parent
class which refers to the subclass object.
 Since we are accessing the data member which is not overridden, hence it
will access the data member of the Parent class always.
class Bike{
int speedlimit = 90;
}
class Honda extends Bike{
int speedlimit = 150;
public static void main(String[] args) {
Bike obj = new Honda();
System.out.println(obj.speedlimit); // 90
}
}
Java Runtime Polymorphism with Multilevel Inheritance
class Animal{
void eat() {
System.out.println(“eating”);
}
}
class Dog extends Animal{
void eat() {
System.out.println(“eating meat”);
}
}
class BabyDog extends Dog{
void eat() {
System.out.println(“drinking milk”);
}
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Dog();
Out put:
Animal a3 = new BabyDog();
eating
}
eating meat
}
drinking milk
Accessing Superclass Members
• Sometimes, it may be necessary to access superclass members directly.
• For example, if your method overrides one of its superclass's methods,
you can invoke the overridden method in the superclass.
• This can be done through the use of the super keyword.

• Super keyword is a reference variable which is used to refer immediate


parent class object (Superclass).

• Usage of Java super Keyword:

– super () can be used to refer immediate parent class instance


variable, method, or constructor.
super can be used to invoke parent class method: Ex.
class Animal{
void eat() {
System.out.println(“eating”);
}
}
class Dog extends Animal{
void eat()
System.out.println(“eating meat”);
void bark()
System.out.println(“Barking …”);
void work() {
super.eat();
bark();
}
}
class Main { Output:
public static void main(String[] args) {
Dog d1 = new Dog();
eating
d1.work(); Barking …
}
}
1. Abstract Classes
 A class which is declared as abstract is known as an abstract class.
 It can have abstract and non-abstract methods.
 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 i.e. an abstract class
cannot be directly instantiated with the new operator.

abstract class Animal {


public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

Animal myObj = new Animal(); // will generate an error

 Such objects would be useless, because an abstract class is not fully


defined.
1. Abstract Classes
• Any class that contains one or more abstract methods must also be
declared abstract. Also, no method body is present.
 Syntax: [access-modifier] abstract type methodName();
• You can create a subclass from an abstract class.
• Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be itself declared abstract.
• In abstract classes, you cannot declare abstract constructors, or
abstract static methods.
abstract class Bike {
• An abstract class can have: abstract void run();
}
– data member, class Honda extends Bike {
void run() {
System.out.println("running");
– abstract method, }
public static void main(String[] args) {
– method body (non-abstract method), Bike obj = new Honda();
obj.run();
– constructor, and even main() method. }
}
Another Example
abstract class Bike {
Bike() {
System.out.println("bike is created");
}
abstract void run();
void chageGear() {
System.out.println("bike is created"); Output
}
} bike is created
//Creating a Child class which inherits Abstract class
running safely..
class Honda extends Bike {
public void run() { gear changed
System.out.println("running safely … ");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction {
public static void main(String[] args) {
Bike obj = new Honda();
obj.run();
obj.chageGear();
}
}
Rules in Abstract classes
Rule 1: If there is an abstract method in a class, that class must be
abstract.

class Animal {
abstract void animalSound(); Output: compile time error
}

• If you are extending an abstract class that has an abstract method, you
must either provide the implementation of the method or make this class
abstract.

Rule 2:Not all the methods in an abstract class have to be abstract.


• A class can provide an implementation for some of its methods.
• In fact, you can declare an abstract class that doesn’t have any abstract
methods. In that case, the class can’t be instantiated
Rules in Abstract classes
Rule 3: you can’t create an instance of an abstract class.

– But you can declare a variable using an abstract class as its type.
– Then, use the variable to refer to an instance of any of the
subclasses of the abstract class.

Rule 4: A private method can’t be abstract.

– because a subclass can’t override a private method, and abstract


methods must be overridden.

Rule 5: A class can’t be both abstract and final.

– That would cause a logical paradox: must be inherited and can’t be


inherited at the same time.
– But the point is that because an abstract class can only be used if
you subclass it, and a final class can’t be subclassed, letting you
specify both abstract and final for the same class doesn’t make
sense.
Example

public abstract class Shape { class Rectangle extends Shape {


public abstract double area(); protected double w, h;
public abstract double circumference(); public Rectangle(double w,
} double h) {
class Circle extends Shape { this.w = w;
protected double r; this.h = h;
protected static final double PI = 3.14; }
public Circle(double r) { public double area() {
this.r = r; return w * h;
} }
public double area() { public double circumference() {
return PI * r * r; return 2 * (w + h);
} }
public double circumference() { }
return PI * r * 2;
}

}
2. Interface
• An interface is a blueprint of a class.
• It is a mechanism to achieve abstraction and multiple inheritances.
• We use interface to build loosely-coupled, extensible, testable
application.
• An interface is similar to an abstract class.
• In the Java programming language, an interface is a reference type
• it can only include abstract methods and final fields (constants), but
 there are no method bodies,
 Interfaces cannot be instantiated and
 also it can’t be used as a base class.
 Instead, they can only be implemented by classes or extended by
other interfaces.
Why use Java interface?
• There are reasons to use interface.

 It is used to achieve abstraction.

 By interface, we can support the functionality of multiple inheritances.

i.e. Interfaces are easier to work with than inheritance, because you
don’t have to worry about providing any implementation details in
the interface.

 A class can extend only one other class, but it can implement as
many interfaces as you need.
How to declare an interface?
 An interface is declared by using the interface keyword.

 It provides total abstraction; means all the methods in an interface are


declared with the empty body, and all the fields are public, static and
final by default.

 A class that implements an interface must implement all the methods


declared in the interface.

 Syntax that defines an interface:

[access-modifier] interface Animal {


constants;
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
How to declare an interface?...
 Variables can be declared inside interface declarations.
 They are implicitly final and static, meaning they cannot be changed by
the implementing class.
 They must also be initialized with a constant value.
 All methods and variables are implicitly public if the interface, itself, is
declared as public.
 So, the interface fields are automatically assumed to be static, final,
and public.
 You can include these keywords when you create interface constants, but
you don’t have to.
Example

 In this example, Java compiler adds public and abstract keywords


before the interface method.
 Moreover, it adds public, static and final keywords before data
members.
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.
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:
[acces_modifier] class ClassName [extends] implements interface
[interface,,]{
// class body
}
Implementing Interfaces: How its works?
 Here, access is either public or not used.
 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.
Interface Example #1:
 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 {
public void print() {
System.out.println("Hello");
}
public void show() {
System.out.println(“Welcome");
}
public static void main(String[] args) {
A6 obj = new A6();
obj.print();
}
} Output: Hello
Interface Example #2: Drawable
 In this example, the Drawable interface has only one method.
 Its implementation is provided by Rectangle and Circle classes.
 In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers.
 Moreover, it is used by someone else. The implementation part is hidden
by the user who uses the interface.
Sample Solution

//Interface declaration: by first user


interface Drawable {
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable {
public void draw() {
System.out.println("drawing rectangle");
}
}
Output:
class Circle implements Drawable {
public void draw() { drawing circle
System.out.println("drawing circle");
}
}
class TestInterface { //Using interface: by third user
public static void main(String[] args) {
Drawable obj = new Circle();
// In real scenario, object is provided by method e.g.
obj.draw();
}
}
Multiple inheritance in Java by interface
 If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritances.
interface Printable {
void print();
}
interface Showable {
void show();
}
class A7 implements Printable, Showable {
public void print() {
System.out.println("Hello");
}
public void show() {
System.out.println(“Welcome");
}
public static void main(String[] args) {
A7 obj = new A7();
obj.print();
obj.show();
} Output: Hello
} Welcome
 Q) Multiple inheritances are not supported through class in java, but it is
possible by an interface, why?
 As we have explained in the inheritance section, multiple inheritances are
not supported in the case of class because of ambiguity.
 However, it is supported in case of an interface because there is no
ambiguity.
 It is because its implementation is provided by the implementation
class.
 Look at next example:
Example: multiple Interface

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

• As you can see in this example, Printable and Showable interface have same
methods
• but its implementation is provided by class TestTnterface, so there is no
ambiguity.
Interface inheritance

A class implements an interface, but one interface


extends another interface.
interface Printable {
void print();
}
interface Showable extends Printable {
void print();
}
class TestInterface implements Showable { Output: Hello
public void print() {
System.out.println("Hello"); Welcome
}
public void show() {
System.out.println(“Welcome");
}
public static void main(String[] args) {
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}
Static Method in Interface

Interface Drawable {
void draw();
static int cube(int x) {
return x*x*x;
}

}
class Rectangle implements Drawable { Output:
public void draw() { drawing rectangle
System.out.println("drawing rectangle");
} 27
}
class TestInterfaceStatic {
public static void main(String[] args) {
Drawable d = new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}
}
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();
}
}
Difference between abstract class and interface.

Abstract class Interface

Abstract class can have abstract Interface can have only


and non-abstract methods. abstract methods

Abstract class doesn't support Interface supports multiple


multiple inheritance inheritance.

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

Abstract class can provide the Interface can't provide the


implementation of interface implementation of abstract class.

The abstract keyword is used to The interface keyword is used to


declare abstract class declare interface.
Difference between abstract class and interface.

Abstract class Interface

An abstract class can extend An interface can extend another


another Java class and implement Java interface only.
multiple Java interfaces.
An abstract class can be extended An interface can be implemented
using keyword "extends". using keyword "implements".

A Java abstract class can have Members of a Java interface are


class members like private, public by default.
protected, etc.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Example of abstract class and interface in Java

//Let's see a simple example where we abstract class B implements A {


are using interface and abstract class public void c(){
both. System.out.println(“I am C”);
//Creating interface that has 4 methods }
}

//Creating subclass of abstract class, now we


Interface A {
need to provide the implementation of rest o
void a();
f the methods
void b();
void c(); class M extends B {
void d(); public void a(){
} System.out.println(“I am A”);
}
//Creating abstract class that provides t public void a(){
he implementation of one method of A i System.out.println(“I am B”);
nterface }
public void a(){
System.out.println(“I am D”);
}
}
Cont…

//Creating a test class that calls the methods of A


interface • Output:
class Main { • I am A
public static void main(String[] args){
A a = new M(); • I am B
a.a();
a.b(); • I am C
a.c();
a.d(); • I am D
}
}
Java Enums

 The enum data type (also known as Enumerated Data Type) is a data
type which contains a fixed set of constants (a variable that does not
change).

 It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) ,

 directions (NORTH, SOUTH, EAST, and WEST), season (SPRING,


SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW,
BLUE, GREEN, WHITE, and BLACK) etc.

 According to the Java naming conventions, we should have all constants


in capital letters.

 So, we have enum constants in capital letters.


Points to remember for Java Enum
 Enum improves type safety
 Enum can be easily used in switch
 Enum can be traversed
 Enum can have fields, constructors and methods
 Enum may implement many interfaces but cannot extend any class
because it internally extends Enum class

class EnumExample1 {
//defining the enum inside the class
public enum Season {WINTER, SPRING, SUMMER, FALL}
//main method Output:
public static void main (String[] args) {
// traversing the enum WINTER
for (Season s : Season.values()); SPRING
System.out.println(s);
} SUMMER
}
FALL

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy