SlideShare a Scribd company logo
1 of 24
Abstract Classes
and Interfaces
Ahmed Nobi
Notes before starting
• Red color font for external sources
- javatpoint.com
- docs.oracle.com
- beginnersbook.com
• Orange color font for” Introduction to Java programming comprehensive
version [Tenth Edition] written by Y. Daniel Liang” source
Also self effors
Abstract Class
- An abstract class cannot be used to create objects. An abstract class can contain abstract
methods, which are implemented in concrete subclasses.
- An abstract class is a class that is declared abstract—it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be sub classed.
Let us discuss a point. All of us know the regular class. A class is basic building block of an object-oriented language. So
what does it mean by abstract class ?. we can answer it later. But first we need to show up some concepts may you faced it
before such as Inheritance.
Overview about Inheritance
• Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
Why use inheritance in java ?
• For Method Overriding (so runtime
polymorphism can be achieved).
• For Code Reusability.
Types of inheritance in java
On the basis of class, there can be three types of
inheritance in java: single, multilevel and hierarchical.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
“ In the inheritance hierarchy, classes become more specific and concrete with each new subclass. If
you move from a subclass back up to a superclass, the classes become more general and less
specific. Class design should ensure that a superclass contains common features of its subclasses.
Sometimes a superclass is so abstract that it cannot be used to create any specific instances. Such a
class is referred to as an abstract class.”
Which means every subclass you create its has own behaviors and fields but also it has a common behaviors which
inheritances it from parent classes. Also when you check the pervious diagram of inheritance types especially
hierarchal type, you will find the class C and B have common behaviors which are inherited from parent. That make us
wonder if we have more than C and B classes and all of them are extended from A class which means all of them have
common behaviors. For ex: our School it has students, Professors and employees, if we need a program that tells the
user who are the students of that school ?, who are the professors ? And who are employees ? Just give the user
their names and few data.
We notice that all of them students, professors and employees have common methods
Public string getName () {
return name ;
}
and so on for getAge() , getID() …
Conclusion
• If we implement it through only the inheritance concept, we will face
a problem that all of them have different fields and methods also
there are some important methods we need to ensure that some
methods will be overridden like getters. Now we are close enough to
get what the abstract class is. “a superclass is so abstract that it
cannot be used to create any specific instances. Such a class is
referred to as an abstract class.” and that the answer of our per
question “what does it mean by abstract class ?”
How to use In Java ?
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to
change the body of the method.
for example
abstract class A {}
Abstract Methods
• “An abstract method is defined without implementation. Its implementation is
provided by the subclasses. A class that contains abstract methods must be defined
as abstract.
The constructor in the abstract class is defined as protected, because it is used only
by subclasses. When you create an instance of a concrete subclass, its superclass’s
constructor is invoked to initialize data fields defined in the superclass”
• A method without body (no implementation) is known as abstract method.
For example
abstract class A {
abstract void print() ;
}
Simple example
• This example show how to create abstract class and
methods
public abstract class A {
public abstract void print();
}
public class B extends A {
@Override
Public void print(){
System.out.println(“Hello World!”)
}
}
Class B extends
Class A
Abstract methods must
be overridden in
subclasses
Abstract methods must be
defined in abstract classes
Let’s code…..
Code of simple example
public abstract class Faculty {
public abstract void setName (String x) ;
public abstract String getName () ;
public abstract void setAge(int x) ;
public abstract int getage () ;
public abstract void setID (int x) ;
public abstract int getID () ;
}
public class Professors extends
Faculty {
private String name ;
private int age ;
private int ID ;
private int salary ;
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public void setName(String x) {
this.name = x ;
}
@Override
public String getName() {
return this.name ;
}
@Override
public void setAge(int x)
{
this.age = x ;
}
@Override
public int getage() {
return this.age ;
}
@Override
public void setID(int x) {
this.ID = x ;
}
@Override
public int getID() {
return this.ID ;
}
}
public class Student extends Faculty {
private String name ;
private int age ;
private int ID ;
private int score ;
private int level ;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
@Override
public void setName(String x) {
this.name = x ;
}
@Override
public String getName() {
return this.name ;
}
@Override
public void setAge(int x) {
this.age = x ;
}
@Override
public int getage() {
return this.age ;
}
@Override
public void setID(int x) {
this.ID = x ;
}
@Override
public int getID() {
return this.ID ;
}
}
Interesting Points about Abstract Classes
The following points about abstract classes are worth noting
â–  An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract
superclass does not implement all the abstract methods, the subclass must be defined as abstract.
In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods
must be implemented. Also note that abstract methods are nonstatic.
â–  An abstract class cannot be instantiated using the new operator, but you can still define its
constructors, which are invoked in the constructors of its subclasses. For instance.
â–  A class that contains abstract methods must be abstract. However, it is possible to define an
abstract class that doesn’t contain any abstract methods. In this case, you cannot create instances
of the class using the new operator. This class is used as abase class for defining subclasses.
â–  A subclass can override a method from its superclass to define it as abstract. This is
very unusual, but it is useful when the implementation of the method in the superclass
becomes invalid in the subclass. In this case, the subclass must be defined as abstract.
â–  A subclass can be abstract even if its superclass is concrete. For example, the Object
class is concrete, but its subclasses, such as GeometricObject, may be abstract.
â–  You cannot create an instance from an abstract class using the new operator, but an
abstract class can be used as a data type. Therefore, the following statement, which
creates an array whose elements are of the GeometricObject type, is correct.
GeometricObject[] objects = new GeometricObject[10];
An Interface
- An interface is a class-like construct that contains only constants and abstract methods. In
many ways an interface is similar to an abstract class, but its intent is to specify common
behavior for objects of related classes or unrelated classes.
- 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.
- An interface is treated like a special class in Java. Each interface is compiled into a
separate
bytecode file, just like a regular class. You can use an interface more or less the same way
you use an abstract class. For example, you can use an interface as a data type for a
reference
variable, as the result of casting, and so on. As with an abstract class, you cannot create an
instance from an interface using the new operator.
What does abstraction mean ?! We will answer that question Later
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
interface A {
//abstract methods
//constants
}
public class B implements A { //@Override Methods }
• “ The relationship between the class and the interface is known as interface inheritance. Since interface
inheritance and class inheritance are essentially the same, we will simply refer to both as inheritance. “
• “Interface fields are public, static and final by default, and the methods are public and abstract”
• “Since all data fields are public static final and all methods are public abstract
in an interface, Java allows these modifiers to be omitted.”
• For example
interface A {
void m1();
}
class B implements A {
@Override
void m1() {
System.out.println("m1");
}
}
Lets code
An interface is declared by using “ interface” keyword
Overridden methods, and notice that w don’t use
abstract Keyword to override it, but an interface
by default abstracted it
That’s how to inherits the interface
to class.
The Comparable interface
The Comparable interface defines the compareTo method for comparing objects
Suppose you want to design a generic method to find the larger of two objects of the same
type, such as two students, two dates, two circles, two rectangles, or two squares. In order to
accomplish this, the two objects must be comparable, so the common behavior for the objects
must be comparable. Java provides the Comparable interface for this purpose. The interface
is defined as follows:
// Interface for comparing objects, defined in java.lang
package java.lang;
public interface Comparable<E> {
public int compareTo(E o);
}
The compareTo method determines the order of this object with the specified object o and
returns a negative integer, zero, or a positive integer if this object is less than, equal to, or
greater than o.
The Comparable interface is a generic interface. The generic type E is replaced by a
concrete type when implementing this interface.
Examples
The Cloneable Interface
The Cloneable interface specifies that an object can be cloned
Often it is desirable to create a copy of an object. To do this, you need to use the clone
method and understand the Cloneable interface.
An interface contains constants and abstract methods, but the Cloneable interface is a
special case. The Cloneable interface in the java.lang package is defined as follows:
package java.lang;
public interface Cloneable {
}
This interface is empty. An interface with an empty body is referred to as a marker
interface. A marker interface does not contain constants or methods. It is used to denote
that a class
possesses certain desirable properties. A class that implements the Cloneable interface is
marked cloneable, and its objects can be cloned using the clone() method defined in the
Object class
Many classes in the Java library (e.g., Date, Calendar, and ArrayList) implement
Cloneable. Thus, the instances of these classes can be cloned. For example, the
following code
Calendar calendar = new GregorianCalendar(2013, 2, 1);
Calendar calendar1 = calendar;
Calendar calendar2 = (Calendar)calendar.clone();
System.out.println("calendar == calendar1 is " +(calendar == calendar1));
System.out.println("calendar == calendar2 is " + (calendar == calendar2));
System.out.println("calendar.equals(calendar2) is " +
calendar.equals(calendar2));
displays
calendar == calendar1 is true
calendar == calendar2 is false
calendar.equals(calendar2) is true
Interfaces VS Abstract Classes
“A class can implement multiple interfaces, but it can only extend one
superclass “ and that’s the main point, you can implements more than one
interface, but you cannot extend more than one abstract class. In other word you
can inherits just only one abstract class, but you can inherits more than one
interface
Abstraction in Java side Information
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
How to achieve the abstraction ?
- Abstract classes
- Interfaces
“ In general, interfaces are preferred over abstract classes because an
interface can define a common super type for unrelated classes.
Interfaces are more flexible than classes. “
Thanks for attention

More Related Content

What's hot

Design patterns
Design patternsDesign patterns
Design patternsLuis Goldster
 
OOP java
OOP javaOOP java
OOP javaxball977
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classesAnup Burange
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
OOPS In JAVA.pptx
OOPS In JAVA.pptxOOPS In JAVA.pptx
OOPS In JAVA.pptxSachin33417
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract ClassOUM SAOKOSAL
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oopMustafaIbrahimy
 
Method overriding
Method overridingMethod overriding
Method overridingAzaz Maverick
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
Java inheritance
Java inheritanceJava inheritance
Java inheritanceBHUVIJAYAVELU
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 

What's hot (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Design patterns
Design patternsDesign patterns
Design patterns
 
OOP java
OOP javaOOP java
OOP java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Basic of Java
Basic of JavaBasic of Java
Basic of Java
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
OOPS In JAVA.pptx
OOPS In JAVA.pptxOOPS In JAVA.pptx
OOPS In JAVA.pptx
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
Method overriding
Method overridingMethod overriding
Method overriding
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Java rmi
Java rmiJava rmi
Java rmi
 
Interface
InterfaceInterface
Interface
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 

Similar to Abstraction in java [abstract classes and Interfaces

Similar to Abstraction in java [abstract classes and Interfaces (20)

Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Oop
OopOop
Oop
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptx
 
Java basics
Java basicsJava basics
Java basics
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Unit 4
Unit 4Unit 4
Unit 4
 
C# program structure
C# program structureC# program structure
C# program structure
 
Classes2
Classes2Classes2
Classes2
 
Lecture 10
Lecture 10Lecture 10
Lecture 10
 
When to use abstract class and methods in java
When to use abstract class and methods in java When to use abstract class and methods in java
When to use abstract class and methods in java
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Java 6.pptx
Java 6.pptxJava 6.pptx
Java 6.pptx
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 

Recently uploaded

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Recently uploaded (20)

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

Abstraction in java [abstract classes and Interfaces

  • 2. Notes before starting • Red color font for external sources - javatpoint.com - docs.oracle.com - beginnersbook.com • Orange color font for” Introduction to Java programming comprehensive version [Tenth Edition] written by Y. Daniel Liang” source Also self effors
  • 3. Abstract Class - An abstract class cannot be used to create objects. An abstract class can contain abstract methods, which are implemented in concrete subclasses. - An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be sub classed. Let us discuss a point. All of us know the regular class. A class is basic building block of an object-oriented language. So what does it mean by abstract class ?. we can answer it later. But first we need to show up some concepts may you faced it before such as Inheritance.
  • 4. Overview about Inheritance • Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Why use inheritance in java ? • For Method Overriding (so runtime polymorphism can be achieved). • For Code Reusability. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
  • 5. Terms used in Inheritance • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
  • 6. “ In the inheritance hierarchy, classes become more specific and concrete with each new subclass. If you move from a subclass back up to a superclass, the classes become more general and less specific. Class design should ensure that a superclass contains common features of its subclasses. Sometimes a superclass is so abstract that it cannot be used to create any specific instances. Such a class is referred to as an abstract class.” Which means every subclass you create its has own behaviors and fields but also it has a common behaviors which inheritances it from parent classes. Also when you check the pervious diagram of inheritance types especially hierarchal type, you will find the class C and B have common behaviors which are inherited from parent. That make us wonder if we have more than C and B classes and all of them are extended from A class which means all of them have common behaviors. For ex: our School it has students, Professors and employees, if we need a program that tells the user who are the students of that school ?, who are the professors ? And who are employees ? Just give the user their names and few data. We notice that all of them students, professors and employees have common methods Public string getName () { return name ; } and so on for getAge() , getID() …
  • 7. Conclusion • If we implement it through only the inheritance concept, we will face a problem that all of them have different fields and methods also there are some important methods we need to ensure that some methods will be overridden like getters. Now we are close enough to get what the abstract class is. “a superclass is so abstract that it cannot be used to create any specific instances. Such a class is referred to as an abstract class.” and that the answer of our per question “what does it mean by abstract class ?”
  • 8. How to use In Java ? • An abstract class must be declared with an abstract keyword. • It can have abstract and non-abstract methods. • It cannot be instantiated. • It can have constructors and static methods also. • It can have final methods which will force the subclass not to change the body of the method. for example abstract class A {}
  • 9. Abstract Methods • “An abstract method is defined without implementation. Its implementation is provided by the subclasses. A class that contains abstract methods must be defined as abstract. The constructor in the abstract class is defined as protected, because it is used only by subclasses. When you create an instance of a concrete subclass, its superclass’s constructor is invoked to initialize data fields defined in the superclass” • A method without body (no implementation) is known as abstract method. For example abstract class A { abstract void print() ; }
  • 10. Simple example • This example show how to create abstract class and methods public abstract class A { public abstract void print(); } public class B extends A { @Override Public void print(){ System.out.println(“Hello World!”) } } Class B extends Class A Abstract methods must be overridden in subclasses Abstract methods must be defined in abstract classes Let’s code…..
  • 11. Code of simple example public abstract class Faculty { public abstract void setName (String x) ; public abstract String getName () ; public abstract void setAge(int x) ; public abstract int getage () ; public abstract void setID (int x) ; public abstract int getID () ; }
  • 12. public class Professors extends Faculty { private String name ; private int age ; private int ID ; private int salary ; public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public void setName(String x) { this.name = x ; } @Override public String getName() { return this.name ; } @Override public void setAge(int x) { this.age = x ; } @Override public int getage() { return this.age ; } @Override public void setID(int x) { this.ID = x ; } @Override public int getID() { return this.ID ; } } public class Student extends Faculty { private String name ; private int age ; private int ID ; private int score ; private int level ; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } @Override public void setName(String x) { this.name = x ; } @Override public String getName() { return this.name ; } @Override public void setAge(int x) { this.age = x ; } @Override public int getage() { return this.age ; } @Override public void setID(int x) { this.ID = x ; } @Override public int getID() { return this.ID ; } }
  • 13. Interesting Points about Abstract Classes The following points about abstract classes are worth noting â–  An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined as abstract. In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented. Also note that abstract methods are nonstatic. â–  An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses. For instance. â–  A class that contains abstract methods must be abstract. However, it is possible to define an abstract class that doesn’t contain any abstract methods. In this case, you cannot create instances of the class using the new operator. This class is used as abase class for defining subclasses.
  • 14. â–  A subclass can override a method from its superclass to define it as abstract. This is very unusual, but it is useful when the implementation of the method in the superclass becomes invalid in the subclass. In this case, the subclass must be defined as abstract. â–  A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract. â–  You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type. Therefore, the following statement, which creates an array whose elements are of the GeometricObject type, is correct. GeometricObject[] objects = new GeometricObject[10];
  • 15. An Interface - An interface is a class-like construct that contains only constants and abstract methods. In many ways an interface is similar to an abstract class, but its intent is to specify common behavior for objects of related classes or unrelated classes. - 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. - An interface is treated like a special class in Java. Each interface is compiled into a separate bytecode file, just like a regular class. You can use an interface more or less the same way you use an abstract class. For example, you can use an interface as a data type for a reference variable, as the result of casting, and so on. As with an abstract class, you cannot create an instance from an interface using the new operator. What does abstraction mean ?! We will answer that question Later
  • 16. 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 interface A { //abstract methods //constants } public class B implements A { //@Override Methods }
  • 17. • “ The relationship between the class and the interface is known as interface inheritance. Since interface inheritance and class inheritance are essentially the same, we will simply refer to both as inheritance. “ • “Interface fields are public, static and final by default, and the methods are public and abstract” • “Since all data fields are public static final and all methods are public abstract in an interface, Java allows these modifiers to be omitted.” • For example interface A { void m1(); } class B implements A { @Override void m1() { System.out.println("m1"); } } Lets code An interface is declared by using “ interface” keyword Overridden methods, and notice that w don’t use abstract Keyword to override it, but an interface by default abstracted it That’s how to inherits the interface to class.
  • 18. The Comparable interface The Comparable interface defines the compareTo method for comparing objects Suppose you want to design a generic method to find the larger of two objects of the same type, such as two students, two dates, two circles, two rectangles, or two squares. In order to accomplish this, the two objects must be comparable, so the common behavior for the objects must be comparable. Java provides the Comparable interface for this purpose. The interface is defined as follows: // Interface for comparing objects, defined in java.lang package java.lang; public interface Comparable<E> { public int compareTo(E o); } The compareTo method determines the order of this object with the specified object o and returns a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than o. The Comparable interface is a generic interface. The generic type E is replaced by a concrete type when implementing this interface.
  • 20. The Cloneable Interface The Cloneable interface specifies that an object can be cloned Often it is desirable to create a copy of an object. To do this, you need to use the clone method and understand the Cloneable interface. An interface contains constants and abstract methods, but the Cloneable interface is a special case. The Cloneable interface in the java.lang package is defined as follows: package java.lang; public interface Cloneable { } This interface is empty. An interface with an empty body is referred to as a marker interface. A marker interface does not contain constants or methods. It is used to denote that a class possesses certain desirable properties. A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using the clone() method defined in the Object class
  • 21. Many classes in the Java library (e.g., Date, Calendar, and ArrayList) implement Cloneable. Thus, the instances of these classes can be cloned. For example, the following code Calendar calendar = new GregorianCalendar(2013, 2, 1); Calendar calendar1 = calendar; Calendar calendar2 = (Calendar)calendar.clone(); System.out.println("calendar == calendar1 is " +(calendar == calendar1)); System.out.println("calendar == calendar2 is " + (calendar == calendar2)); System.out.println("calendar.equals(calendar2) is " + calendar.equals(calendar2)); displays calendar == calendar1 is true calendar == calendar2 is false calendar.equals(calendar2) is true
  • 22. Interfaces VS Abstract Classes “A class can implement multiple interfaces, but it can only extend one superclass “ and that’s the main point, you can implements more than one interface, but you cannot extend more than one abstract class. In other word you can inherits just only one abstract class, but you can inherits more than one interface
  • 23. Abstraction in Java side Information Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it. How to achieve the abstraction ? - Abstract classes - Interfaces “ In general, interfaces are preferred over abstract classes because an interface can define a common super type for unrelated classes. Interfaces are more flexible than classes. “