0% found this document useful (0 votes)
2 views47 pages

Abstract class and Interface

The document explains the concepts of abstract classes and interfaces in Java, detailing how abstract methods enforce implementation in subclasses and how interfaces define common behaviors for objects. It provides examples of abstract classes like Person and Bank, as well as interfaces like Shape and Edible, illustrating their usage and characteristics. Additionally, it discusses the limitations of abstract classes and interfaces, such as the inability to instantiate them directly and the rules governing their implementation and inheritance.

Uploaded by

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

Abstract class and Interface

The document explains the concepts of abstract classes and interfaces in Java, detailing how abstract methods enforce implementation in subclasses and how interfaces define common behaviors for objects. It provides examples of abstract classes like Person and Bank, as well as interfaces like Shape and Edible, illustrating their usage and characteristics. Additionally, it discusses the limitations of abstract classes and interfaces, such as the inability to instantiate them directly and the rules governing their implementation and inheritance.

Uploaded by

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

Abstract Classes and

Interfaces
In Java
Abstract Methods and Classes
• A class can define a method without an
implementation, forcing subclasses to
implement it.
• Such a method, and the class containing it,
are called abstract and must be tagged with
the abstract modifier.
• This is commonly done for very general
classes.
Abstract Methods and Classes
• Example:
public abstract class Person {
private String name;
public Person(String name) {
this.name = name; }
public final String getName() {
return name; }
public abstract int getId();
}
• Any class extending Person must either supply an
implementation of the getId method or be itself
declared as abstract.
• Abstract class can have nonabstract methods, such
as the getName method.
Abstract Class
• It is not possible to construct an instance of an
abstract class.
• For example, the call

Person p = new Person("Fred"); //


Error
would be a compile-time error.
• However, you can have a variable whose type is an abstract
class, provided it contains a reference to an object of a
concrete subclass.
Abstract Class
● Suppose the class Student is declared as
public class Student extends Person {
private int id;
public Student(String name, int id) {
super(name); this.id = id; }
public int getId() { return id; }
}
● So, construct a Student and assign it to a Person

variable.
● Person p = new Student("Fred", 1729);

● // OK, a concrete subclass


• Classes that can be used to instantiate objects are called
concrete classes.
• Such classes provide implementations of every method
they declare (some of the implementations can be
inherited).
• For example, we could derive concrete classes Circle,
Square and Triangle from abstract superclass
TwoDimensionalShape.
• Similarly, we could derive concrete classes Sphere, Cube
and Tetrahedron from abstract superclass
ThreeDimensionalShape.
Abstract Classes and Abstract Methods
Abstract Method in Abstract Class

• 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 abstract.
• In a nonabstract subclass extended from an
abstract class, all the abstract methods must be
implemented, even if they are not used in the
subclass.
Object Cannot Be Created From
Abstract Class
• An abstract class cannot be instantiated
using the new operator, we can define its
constructors, which are invoked in the
constructors of its subclasses.
• For instance, the constructors of
GeometricObject are invoked in the
Circle class and the Rectangle class.
Abstract Class Without Abstract Method
• A class that contains abstract methods must
be abstract.
• However, it is possible to define an abstract
class that contains no abstract methods.
• In this case, we cannot create instances of
the class using the new operator.
• This class is used as a base class for
defining a new subclass.
Superclass of Abstract Class May Be
Concrete
• 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.
Concrete Method Overridden To Be
Abstract
• A subclass can override a method from its
superclass to define it abstract.
• This is rare, but useful when the
implementation of the method in the
superclass becomes invalid in the subclass.
• In this case, the subclass must be defined
abstract.
Abstract Class As Type
• 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
GeometricObject type, is correct.
GeometricObject[] geo = new GeometricObject[10];
Abstract Number Class
Example
abstract class Bank{
Bank(){
System.out.println("Welcome to Banking System");}
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest()
{return 7;}
}
class PNB extends Bank{
int getRateOfInterest()
{return 8;}
}
class TestBank{
public static void main(String args[])
{
// Getting hold of Class object created by JVM.

Bank b;
b=new SBI();
Class c1 = b.getClass();
//Printing object using c1.
System.out.println(c1.getName());
System.out.println(“RoI is: "+b.getRateOfInterest()+" %");b=new
PNB();
Abstract Calendar Class and
Its GregorianCalendar subclass
Abstract Calendar Class and Its
GregorianCalendar subclass
• An instance of java.util.Date represents a
specific instant in time with millisecond precision.
• java.util.Calendar is an abstract base class
for extracting detailed information such as year,
month, date, hour, minute and second from a Date
object.
• Subclasses of Calendar can implement specific
calendar systems such as Gregorian calendar,
Lunar Calendar and Jewish calendar.
• Currently, java.util.GregorianCalendar for
the Gregorian calendar is supported in the Java API.
Calendar Class
• The java.util.Calendar class was added in
Java on JDK 1.4 in an attempt to fix some flaws of
the java.util.Date class.
• An arbitrary date may be created using new
GregorianCalendar(2016, Calendar.JUNE,
11) constructor, as opposed to Date class where
the year starts from 1900 and Month was starting
from zero.
Calendar Class
• The Calendar class provides support for:
• Maintaining a set of calendar fields such as
YEAR, MONTH, DAY_OF_MONTH, HOUR,
MINUTE, SECOND, MILLISECOND; and
manipulating these calendar fields, such as
getting the date of the previous week, roll
forward by 3 days.
Calendar Class
• Calendar provides internationalization
support.
• Calendar.getInstance(): return a
Calendar instance based on the current time
in the default time zone with the default
locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
Calendar.getInstance(TimeZone zone,
Locale aLocale)
The get Method in Calendar Class
• The get(int field) method defined in the Calendar
class is useful to extract the date and time information from
a Calendar object.
• The fields are defined as constants, as shown in the
following.
Example
import java.util.Calendar;
public class GetYMDHMS {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// You cannot use Date class to extract individual Date
fields
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 to 11
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);

System.out.printf("Now is %4d/%02d/%02d
%02d:%02d:%02d\n",
year, day, month+1, hour, minute, second);
}
}
Calendar Class
• The java.util.Calendar class is an
abstract class and you obtain the instance of
a Calendar local to your timezone and Locale
by calling the static getInstance() method
of java.util.Calendar class.
• This method generally returns an instance of
GregorianCalendar class.
GregorianCalendar
• The Gregorian calendar is the calendar which
is used today. It came into effect on October
15, 1582, in some countries.
– In Julian calendar, every four years is a leap year.
• In the Gregorian calendar, a leap year is a
year that is divisible by 4 but not divisible by
100, or it is divisible by 400, i.e., the Gregorian
calendar omits century years which are not
divisible by 400 (removing 3 leap years (or 3
days) for every 400 years).
The GregorianCalendar Class
• You can use new GregorianCalendar()
to construct a default GregorianCalendar
with the current time and use new
GregorianCalendar(year, month,
date) to construct a GregorianCalendar
with the specified year, month, and date.
• The month parameter is 0-based, i.e., 0 is for
January.
Interfaces
• What is an interface?
• Why is an interface useful?
• How do you define an interface?
• How do you use an interface?
What is an interface?
Why is an interface useful?
• An interface is a classlike construct that
contains only constants and abstract
methods.
• An interface is similar to an abstract class,
but the intent of an interface is to specify
common behavior for objects.
• A Class Can Extend Only One Other Class
But Can Implement Many Interfaces
Define an Interface
• To distinguish an interface from a class, Java uses
the following syntax to define an interface:
public interface InterfaceName {
constant declarations;
abstract method signatures;

public interface Edible {


/** Describe how to eat */
public abstract String howToEat();
}
}
Interface is a Special Class
• An interface is treated like a special class in
Java.
• Each interface is compiled into a separate
bytecode file, just like a regular class.
• Like an abstract class, an instance from an
interface using the new operator cannot be
created
• Interface is used similar to an abstract class.
Example

• Class Employee appears in italics, indicating that it’s an


abstract class.
public interface Shape {
//implicitly public, static and final
public String LABLE="Shape";
//interface methods are implicitly abstract and public
void draw();
double getArea();
}

public class ShapeTest {


public static void main(String[] args) {
Shape shape = new Circle(10);
shape.draw();
System.out.println("Area="+shape.getArea());
//switching from one implementation to another easily
shape=new Rectangle(10,10);
shape.draw();
System.out.println("Area="+shape.getArea());
}

}
public class Circle implements Shape
{ private double radius;
public Circle(double r){
this.radius = r;}

@Override public void draw() {


System.out.println("Drawing Circle"); }

@Override public double getArea(){


return Math.PI*this.radius*this.radius;
}
public double getRadius(){
return this.radius;
}
}

public class Rectangle implements Shape {


private double width;
private double height;

public
interface Drawable {
int RED = 1;
int GREEN = 2;
int BLUE = 3;
int BLACK = 4;
int WHITE = 5;
void draw(int color); }
class Draw
{
public static void main(String[] args)
{ Drawable[] drawables
= new Drawable[] { new Circle(10, 20, 15),
new Circle(30, 20, 10),
new Rectangle(5, 8, 8, 9)
};
for (int i = 0; i < drawables.length;
i++)
Another Example of Interface
interface printable{
void print();
}

public class TestInterface implements printable{


@Override
public void print(){
System.out.println("Hello");
}

public static void main(String args[]){


TestInterface obj = new TestInterface();
Interfaces …
public interface Edible {
public abstract String howToEat();
}

abstract class Fruit implements Edible


class Apple extends Fruit

class Mango extends Taste implements Edible

-------------------------------------------------
abstract class Animal {
/** Return animal sound */
public abstract String sound();
}
Array of Objects
Object[] objects={new Tiger(), new Barbet(), new
Apple()};
for (int i = 0; i < objects.length; i++) {
if (objects[i] instanceof Edible)
System.out.println(((Edible)objects[i]).howToEat());

if (objects[i] instanceof Animal) {


System.out.println(((Animal)objects[i]).sound());
}

if (objects[i] instanceof Bird) {


System.out.println(((Bird)objects[i]).colour());
Multiple Inheritance
interface Printable{
void print();
}
interface Showable{
void show();
}
class MultiInheritance implements Printable,Showable{
public void print(){System.out.println("Printing Circle");}
public void show(){System.out.println("Welcome to Circle
Showing");}

public static void main(String args[]){


MultiInheritance obj = new MultiInheritance();
obj.print();
Multiple Inheritance …
interface PrintIt{
void print();
}
interface ShowIt{
void print();
}

class TestInterface implements PrintIt, ShowIt{


public void print(){
System.out.println("Multiple Inheritiance in Java");}
public static void main(String args[]){
TestInterface obj = new TestInterface();
obj.print();
More on Interface
• Concrete class SalariedEmployee extends
Employee, inheriting its superclass’s
realization relationship with interface
Payable.

public interface Payable


{
double getPaymentAmount();
// calculate payment
}
Invoice class implements Payable
public class Invoice implements Payable
{
private final String partNumber;
private final String partDescription;
private int quantity;
private double pricePerItem;

// constructor
public Invoice(String partNumber, String partDescription, int
quantity,double pricePerItem)
{
if (quantity < 0) // validate quantity
throw new IllegalArgumentException("Quantity must be >= 0");

if (pricePerItem < 0.0) // validate pricePerItem


throw new IllegalArgumentException("Price per item must be>= 0");

this.quantity = quantity;
this.partNumber = partNumber;
public String getPartNumber()
{ return partNumber; // should validate
}
// get description
public String getPartDescription()
{ return partDescription;
}
// set quantity
public void setQuantity(int quantity)
{
if (quantity < 0) // validate
throw new IllegalArgumentException("Quantity must be >= 0");
this.quantity = quantity;
}
// get quantity
public int getQuantity()
{ return quantity;
}
// set price per item
Omitting Modifiers in Interfaces
• All data fields are public final static and all methods are
public abstract in an interface.
• For this reason, these modifiers can be omitted, as
shown below:

• A constant defined in an interface can be accessed


using syntax InterfaceName.CONSTANT_NAME
• (e.g., T1.K).
Example: The Comparable Interface
// This interface is defined in java.lang
package java.lang;

public interface Comparable<E> {


public int compareTo(E o);
}
toString, equals, and hashCode
Methods
• Each wrapper class overrides the toString,
equals, and hashCode methods defined in
the Object class.
• Since all the numeric wrapper classes and the
Character class implement the
Comparable interface, the compareTo
method is implemented in these classes.
Integer and BigInteger Classes

String and Date Classes


Examples
1 System.out.println(new Integer(3).compareTo(new
Integer(5)));
2 System.out.println("ABC".compareTo("ABE"));
3 java.util.Date date1 = new java.util.Date(2013, 1, 1);
4 java.util.Date date2 = new java.util.Date(2012, 1, 1);
5 System.out.println(date1.compareTo(date2));

You might also like