0% found this document useful (0 votes)
17 views26 pages

Abstraction

The document explains the concepts of abstract classes and methods in Java, emphasizing data abstraction and its implementation through abstract classes and interfaces. It also covers polymorphism, detailing static and dynamic types, method overloading, and overriding with examples. Additionally, it highlights the importance of abstraction for security, loose coupling, and providing templates for future classes.

Uploaded by

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

Abstraction

The document explains the concepts of abstract classes and methods in Java, emphasizing data abstraction and its implementation through abstract classes and interfaces. It also covers polymorphism, detailing static and dynamic types, method overloading, and overriding with examples. Additionally, it highlights the importance of abstraction for security, loose coupling, and providing templates for future classes.

Uploaded by

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

Oops in java

Abstract Classes and Methods

• Data abstraction is the process of hiding certain details and showing only
essential information to the user.
• Abstraction can be achieved with either abstract classes or interfaces
(which you will learn more about in the next chapter).

• The abstract keyword is a non-access modifier, used for classes and


methods:

• Abstract class: is a restricted class that cannot be used to create objects


(to access it, it must be inherited from another class).

• Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class cat extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The cat says: meow");
}
}
• class Main {
• public static void main(String[] args) {
• Cat mycat = new cat(); // Create a cat object
• myCat.animalSound();
• myCat.sleep();
• }
• }
Why And When To Use Abstract Classes and Methods?

• To achieve security - hide certain details and only show the important
details of an object.

• Note: Abstraction can also be achieved with Interfaces,


How to implement Abstraction in
Java
• Using Abstract Classes
• Declared with the abstract keyword.
• Can have both abstract methods (no body) and concrete methods (with body).
abstract class Animal
{
abstract void sound(); // abstract method

void eat() {
System.out.println("Eating...");
}
}
• Using Interfaces
• Declared using the interface keyword.
• All methods in interfaces are implicitly abstract (until Java 8+).
interface Vehicle
{
void start(); // abstract method}
(Abstract Class vs Interface)
Feature Abstract Class Interface

Keyword abstract class interface

Method Types Abstract & Concrete methods Only abstract (until Java 8)

Constructors Can have constructors Cannot have constructors

Variables Can have variables (non-final) Only public static final

Inheritance One abstract class only (single) Multiple interfaces allowed

Some common implementation is


Use When Total abstraction required
needed
Why Use Abstraction?
• To achieve loose coupling.
• To hide complexity from the user.
• To provide a template or blueprint for future classes.
Abstraction Using interface
Shape
{
void draw();
}
class Circle implements Shape
{
public void draw()
{
System.out.println("Drawing Circle");
}
}
Let us consider a simple example of a class with abstract method, followed by a class that implements that method.

abstract class Bank


{
/*abstract class declaration*/
abstract int getRateOfInterest( );
/*abstract method declaration*/
}
class SBI extends Bank
{
int getRateOfInterest( )
{
/*overriding abstract method*/
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest( )
{
/*overriding abstract method*/
return 8;
}
}
public class TestBank {
public static void main(String[] args) {
Bank b1 = new SBI(); // Upcasting
Bank b2 = new PNB(); // Upcasting

System.out.println("SBI Rate of Interest: " + b1.getRateOfInterest() + "%");


System.out.println("PNB Rate of Interest: " + b2.getRateOfInterest() + "%");
}
}
Polymorphism

• Polymorphism literally means “having many forms” and is used as a


feature in objectoriented
• programming that provides one interface for a general class of actions.
The
• specific action is implemented to address the exact nature of the
situation.
Polymorphism in Java is the ability of an entity to take many forms as per requirement. a man standing in the middle is
only one, but he takes multiple roles like a dad for his children, an employee, a salesperson, and many
more. This is known as polymorphism because one person taking many roles.

Another example may be the saving of two contact numbers of the same person. What we do for
this? We save these two numbers with the same name or in other words both number can be
saved in one contact name only. That is also a kind of
polymorphism. In a similar fashion, in java programming, one object can take multiple forms
depending on the context of the program.
TYPES OF POLYMORPHISM

• • Static Polymorphism
• • Dynamic Polymorphism

• Polymorphism
• Overloading
• Overloading method where more than one methods Share the same name with different parameters or
signature and different return type
• Overriding
Overriding method of super class by method of child class, which is done By JVM

• Occurs during Compile time --- Overloading


• Occurs during Run time----- Overriding
• Static polymorphism is also known as compile-time polymorphism because
compiler resolves the polymorphism during the compilation of the program by
checking the method signatures. Static polymorphism can be achieved through
method overloading with the same name but different parameters., which means the
name of the methods is the same but the signature of the methods is different.

• Dynamic polymorphism is also known as run time polymorphism because


JVM(Java Virtual Machine) resolves the call to an overridden method at the runtime
of the program. Dynamic polymorphism can be achieved by method overriding with
the same name and parameters but in different classes.In the coming sections, you
will
learn more about method overloading and method overriding in detail.
OVERLOADING OF METHOD
• There are three ways to overload a method:
1. There are different number of parameters in the argument list of the
methods.
Example: sum(int, int)
sum(int, int, int)
2. There are different data types of the parameters in the argument list.
Example: sum(float, float)
sum(float, int)
3. There is a different sequence of data types of the parameters.
Example: sum(float, int)
sum(int, float)
• Let us discuss the programming aspects of polymorphism of Java with the help of a
• simple example in which “Animal” is a parent class and “Cat” is a child class. Both the parent and child classes are using the same
method makeSound( ).

class Animal
{
/*Animal is a parent class*/
void makeSound()
{
System.out.println(“Now Speak!”);
}
}
class Cat extends Animal{
/*Cat is a child class*/
void makeSound()
{
System.out.println(“Meow”);
}
}
class PolymorphismExample
{
public static void main(String args[])
Animal a = new Animal(); /*creating object*/
Cat d = new Cat(); /*creating object*/
a.makeSound();
d.makeSound();
}
}

• Output:
Now Speak!
Meow

• In the above example program, you can see that both the classes are using the same
method in different ways.
class TestBank
{
public static void main(String args[])
{
Bank b; /*cannot be directly instantiated with new operator*/
b = new SBI( );
System.out.println("Rate of Interest is: " + b.getRateOfInterest() + "%");
b = new PNB( );
System.out.println("Rate of Interest is: " + b.getRateOfInterest() + "%");
}
}
• Output:
• Rate of Interest is: 7%
• Rate of Interest is: 8%
• The above example consists of one superclass Bank which is declared abstract with
an
• abstract method getRateOfInterest( ). SBI and PNB are two subclasses, overriding the
• method getRateOfInterest( ).
OVERRIDING OF METHOD
• Overriding the method in Java is one of the ways to achieve runtime polymorphism.

class Figure
{
/*Using runtime polymorphism*/
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
double area( )
{
System.out.println(“Area for Figure is undefined.”);
return 0;
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}
double area( )
{
/*Override area for Rectangle*/
System.out.println(“Inside Area for Rectangle.”);
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
double area( )
{
/*Override area for Right Triangle*/
System.out.println(“Inside Area for Triangle.”);
return dim1 * dim2 / 2;
}
}class FindAreas
{
public static void main(String args[])
{
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure ref;
ref = r;
System.out.println(“Area is ” + ref.area( ));
ref = t;
System.out.println(“Area is ” + ref.area( ));
ref = f;
System.out.println(“Area is ” + ref.area( ));
}
}
• In the above example, there is a superclass called Figure that stores the dimensions of two-
dimensional objects. It also defines the method area( ) that calculates the area of an
object.
• The two subclasses: Rectangle and Triangle are derived from the superclass
• Figure. Both the subclasses override the method area( ) to return their respective areas.

• Certain rules must be followed while overriding the methods:


1. While overriding child class method signature and parent class method signatures must be
the same; otherwise, it will generate compilation error.
2 The return types of overridden method and overriding method must be the same.
3. Methods declared final cannot be overridden.
4. Static methods are bounded with class. Hence, it cannot be overridden.
5. The access level of methods cannot be more restrictive than the overridden method’s
access level.
method overloading.
package overloadingtest;
class DemoOverload
{
void test( )
{
System.out.println("No parameters");
}
/*------overload test for one integer parameter-------*/
void test(int a)
{
System.out.println("a : " + a);
}
/*------overload test for two integer parameters-------*/
void test(int a, int b)
{
System.out.println("a and b : " + a + " " + b);

/*------overload test or a double parameter-------*/


double test(double a){
System.out.println("double a :" + a);
return a*a;
class MyOverloading
{
public static void main(String args[])
{
DemoOverload obj = new DemoOverload( );
double result;
/*-------call all versions of test( )-------*/
obj.test( );
obj.test(10);
obj.test(10,20);
result = obj.test(123.25);
System.out.println("Result of obj.test(123.25) :" + result);
}
Let’s take an example-based on employee and department to discuss the abstract class and abstract method

abstract class Employee


{
final int salary = 20000;
public void display()
{
System.out.println(“This is a method to display the employee information.”);
}
abstract public void Department();
}
public class Teacher extends Employee
{
public static void main(String args[])
{
Teacher obj = new Teacher();
obj.display();
obj.Department();
//obj.salary=30000;
}
/*public void Department()
{
System.out.println("Computer Science Department");
}
*/
}

You might also like