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

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Friend functions
Friend functions Friend functions
Friend functions
Megha Singh
 

What's hot (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
C# Encapsulation
C# EncapsulationC# Encapsulation
C# Encapsulation
 
Inline function
Inline functionInline function
Inline function
 
OOP C++
OOP C++OOP C++
OOP C++
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Virtual function and abstract class
Virtual function and abstract classVirtual function and abstract class
Virtual function and abstract class
 
Friend functions
Friend functions Friend functions
Friend functions
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)
 
Ch2 Liang
Ch2 LiangCh2 Liang
Ch2 Liang
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Inheritance
InheritanceInheritance
Inheritance
 

Similar to Abstraction in java [abstract classes and Interfaces

9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 

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

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 

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