SlideShare a Scribd company logo
2
Most read
10
Most read
12
Most read
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

PPTX
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
PPTX
Abstraction in java
sawarkar17
 
PPTX
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
PDF
Method Overloading In Java
CharthaGaglani
 
PPT
06 abstract-classes
Anup Burange
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPSX
ADO.NET
Farzad Wadia
 
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
Abstraction in java
sawarkar17
 
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Method Overloading In Java
CharthaGaglani
 
06 abstract-classes
Anup Burange
 
Classes, objects in JAVA
Abhilash Nair
 
ADO.NET
Farzad Wadia
 

What's hot (20)

PDF
Introduction to Java Programming Language
jaimefrozr
 
PPT
Java interfaces
Raja Sekhar
 
PPTX
Super keyword in java
Hitesh Kumar
 
PPTX
Control structures in java
VINOTH R
 
PPTX
Inheritance
Sapna Sharma
 
PPTX
Ado.Net Tutorial
prabhu rajendran
 
PPTX
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 
PPTX
Basics of Object Oriented Programming in Python
Sujith Kumar
 
PPT
C# Exceptions Handling
sharqiyem
 
PDF
C++ OOPS Concept
Boopathi K
 
PPTX
Java string handling
Salman Khan
 
PPTX
Abstract Class Presentation
tigerwarn
 
PPTX
Method overloading
Lovely Professional University
 
PPTX
Inheritance in java
RahulAnanda1
 
PPTX
Association agggregation and composition
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Java abstract class & abstract methods
Shubham Dwivedi
 
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
PPS
Interface
kamal kotecha
 
PPTX
ArrayList in JAVA
SAGARDAVE29
 
PPTX
Inheritance and Interfaces
NAGASURESH MANOHARAN
 
Introduction to Java Programming Language
jaimefrozr
 
Java interfaces
Raja Sekhar
 
Super keyword in java
Hitesh Kumar
 
Control structures in java
VINOTH R
 
Inheritance
Sapna Sharma
 
Ado.Net Tutorial
prabhu rajendran
 
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 
Basics of Object Oriented Programming in Python
Sujith Kumar
 
C# Exceptions Handling
sharqiyem
 
C++ OOPS Concept
Boopathi K
 
Java string handling
Salman Khan
 
Abstract Class Presentation
tigerwarn
 
Method overloading
Lovely Professional University
 
Inheritance in java
RahulAnanda1
 
Association agggregation and composition
baabtra.com - No. 1 supplier of quality freshers
 
Java abstract class & abstract methods
Shubham Dwivedi
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Interface
kamal kotecha
 
ArrayList in JAVA
SAGARDAVE29
 
Inheritance and Interfaces
NAGASURESH MANOHARAN
 
Ad

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

PDF
java-06inheritance
Arjun Shanka
 
PDF
Abstraction in Java: Abstract class and Interfaces
Jamsher bhanbhro
 
PPT
ABSTRACT CLASSES AND INTERFACES.ppt
JayanthiM15
 
PPTX
Abstract Class and Interface for Java Intoductory course.pptx
DrShamimAlMamun
 
PDF
Java abstract Keyword.pdf
SudhanshiBakre1
 
PPT
Java interfaces & abstract classes
Shreyans Pathak
 
PDF
Java 06
Loida Igama
 
PPT
OOPS_AbstractClasses_explained__java.ppt
JyothiAmpally
 
PDF
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
PPT
Java inheritance
Arati Gadgil
 
PDF
Advanced Programming _Abstract Classes vs Interfaces (Java)
Professor Lili Saghafi
 
PPTX
Abstraction in java.pptx
AsifMulani17
 
PPTX
06_OOVP.pptx object oriented and visual programming
deffa5
 
PPTX
Lecture 18
talha ijaz
 
PDF
Abstract classes and Methods in java
Harish Gyanani
 
PPT
Chap11
Terry Yoast
 
PPT
9781439035665 ppt ch10
Terry Yoast
 
DOC
Interface Vs Abstact
Anand Kumar Rajana
 
PPT
Chapter 9 Interface
OUM SAOKOSAL
 
java-06inheritance
Arjun Shanka
 
Abstraction in Java: Abstract class and Interfaces
Jamsher bhanbhro
 
ABSTRACT CLASSES AND INTERFACES.ppt
JayanthiM15
 
Abstract Class and Interface for Java Intoductory course.pptx
DrShamimAlMamun
 
Java abstract Keyword.pdf
SudhanshiBakre1
 
Java interfaces & abstract classes
Shreyans Pathak
 
Java 06
Loida Igama
 
OOPS_AbstractClasses_explained__java.ppt
JyothiAmpally
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
Java inheritance
Arati Gadgil
 
Advanced Programming _Abstract Classes vs Interfaces (Java)
Professor Lili Saghafi
 
Abstraction in java.pptx
AsifMulani17
 
06_OOVP.pptx object oriented and visual programming
deffa5
 
Lecture 18
talha ijaz
 
Abstract classes and Methods in java
Harish Gyanani
 
Chap11
Terry Yoast
 
9781439035665 ppt ch10
Terry Yoast
 
Interface Vs Abstact
Anand Kumar Rajana
 
Chapter 9 Interface
OUM SAOKOSAL
 
Ad

Recently uploaded (20)

PDF
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
PPTX
EU POPs Limits & Digital Product Passports Compliance Strategy 2025.pptx
Certivo Inc
 
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
RanuFajar1
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PPT
Order to Cash Lifecycle Overview R12 .ppt
nbvreddy229
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PDF
Become an Agentblazer Champion Challenge
Dele Amefo
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
EU POPs Limits & Digital Product Passports Compliance Strategy 2025.pptx
Certivo Inc
 
Materi_Pemrograman_Komputer-Looping.pptx
RanuFajar1
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Order to Cash Lifecycle Overview R12 .ppt
nbvreddy229
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
oapresentation.pptx
mehatdhavalrajubhai
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
Exploring AI Agents in Process Industries
amoreira6
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
Become an Agentblazer Champion Challenge
Dele Amefo
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 

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. “