You are on page 1of 45

Abstract Classes

1
Abstract Classes
• When we define a class to be “final”, it
cannot be extended.
• In certain situation, we want properties of
classes to be always extended and used.
Such classes are called Abstract Classes.
• An Abstract class is a conceptual class.
• An Abstract class cannot be instantiated –
objects cannot be created.

2
Abstract Class Syntax
abstract class ClassName {
abstract Type MethodName1( );

Type Method2()
{
// method body
}
}
• When a class contains one or more abstract methods, it
should be declared as abstract class.
• The abstract methods of an abstract class must be
defined in its subclass.
• We cannot declare abstract constructors or abstract
static methods.
3
Abstract Class -Example
• Shape is a abstract class.

Shape

Circle Rectangle

4
The Shape Abstract Class
public abstract class Shape {
public abstract double area();
public void move() { // non-abstract method
// implementation
}
}

• Is the following statement valid?


• Shape s = new Shape();
• No. It is illegal because the Shape class is an abstract
class, which cannot be instantiated to create its
objects.
5
Abstract Classes
public Circle extends Shape {
protected double r;
protected static final double PI =3.1415926535;
public Circle() { r = 1.0; )
public double area() { return PI * r * r; }

}
public Rectangle extends Shape {
protected double w, h;
public Rectangle() { w = 0.0; h=0.0; }
public double area() { return w * h; }
}
6
Abstract Classes Properties
• A class with one or more abstract methods is
automatically abstract and it cannot be
instantiated.
• A class declared abstract, even with no abstract
methods can not be instantiated.
• A subclass of an abstract class can be instantiated
if it overrides all abstract methods by
implementation them.

7
Interfaces
Design Abstraction and a way for realizing
Multiple Inheritance

9
Interfaces
• Interface is a conceptual entity similar to a
Abstract class.
• Can contain only constants (final
variables) and abstract method (no
implementation) - Different from Abstract
classes.
• Use when a number of classes share a
common interface.
• Each class should implement the interface.
10
Interfaces: An informal way of realizing multiple
inheritance
• An interface contains abstract methods and final
variables.

• Therefore, it is the responsibility of the class that


implements an interface to supply the code for
methods.

• A class can implement any number of interfaces,


but cannot extend more than one class at a time.

• Therefore, interfaces are considered as an


informal way of realizing multiple inheritance in
Java. 11
Relationship between classes and interfaces
• As shown in the figure given below, a class extends
another class.
• An interface extends another interface but a class
implements an interface

12
Interface -example

<<Interface>>
Speaker
speak()

Politician Lecturer
speak() speak()

13
Interfaces Definition
• Syntax (appears like abstract class):
interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – no method body
}
• Example:

interface Speaker {
public void speak( );
}

14
The java compiler adds public and abstract keywords
before the interface method and public, static and final
keywords before data members.
15
Implementing Interfaces
• Interfaces are used like super-classes who's
properties are inherited by classes.
• This is achieved by creating a class that
implements the given interface as follows:

class ClassName implements InterfaceName


[,InterfaceName2, …]
{
// Body of Class
}
16
Implementing Interfaces Example
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}

class Lecturer implements Speaker {


public void speak(){
System.out.println(“Talks Object
Oriented Programming!”);
}
} 17
Inheritance and Interface Implementation
• A general form of interface implementation:
class ClassName extends SuperClass implements
InterfaceName [, InterfaceName2, …]
{
// Body of Class
}

• This shows a class can extends another class while


implementing one or more interfaces.
• It appears like a multiple inheritance.

18
Student Assessment Example
• Consider a university where students who participate in
the national games or Olympics are given some grace
marks.
• Therefore, the final marks awarded = Exam_Marks +
Sports_Grace_Marks. A class diagram representing this
scenario is as follow:

Student Sports

extends
Exam
implements
extends

Results
19
Implementation
class Student {
// student Rno and access methods
}
interface Sport {
// sports grace marks (say 5 marks) and abstract methods
}
class Exam extends Student {
// example marks (test1 and test 2 marks) and access methods
}
class Results extends Exam implements Sport {
// implementation of abstract methods of Sport interface
// other methods to compute total marks
// other display or final results access methods
}
20
interface Printable{
void print();
}
interface Showable{
void show();
}
class A implements Printable, Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A obj = new A();
obj.print();
obj.show();
} }
21
Extending Interfaces
• Like classes, interfaces can also be extended.
• The new sub-interface will inherit all the
members of the super-interface in the manner
similar to classes.
• This is achieved by using the keyword extends as
follows:

interface InterfaceName2 extends InterfaceName1 {


// Body of InterfaceName2
}

22
interface Printable {
void print(); }
interface Showable extends Printable{
void show(); }

class A implements Showable{


public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]) {


A obj = new A();
obj.print();
obj.show();
} } 23
Abstract class Vs Interface
1. abstract class can extend only one class or one
abstract class at a time Where as interface can
extend any number of interfaces at time.
2. abstract class can be extended from a class or
from an abstract class Where as interface can be
extended only from an interface.
3. abstract class can have both abstract and
concrete methods Where as interface can have
only abstract methods.
4. A class can extend only one abstract class Where
as a class can implement any number of
interfaces.
24
Abstract class Vs Interface
5. In abstract class keyword ‘abstract’ is used to declare
a method as an abstract where as In an interface
keyword ‘abstract’ is optional to declare a method as
an abstract

6. abstract class can have protected , public and public


abstract methods where as Interface can have only
public abstract methods i.e. by default

7. abstract class can have static, final or static final


variable with any access specifier where as interface
can have only static final (constant) variable i.e. by
default
25
DIFFERENCES BETWEEN
CLASSES AND
INTERFACES

26
Class Interface
Class is user defined type Interface is a java object.
Starts with keyword “class” Starts with keyword
“interface”
Class contains one or more Interface contains all
or no abstract methods abstract methods and final
declarations.
The variables can have any The Variables should be
access specifier. public, static, final
Multiple inheritance is not It is possible
possible
Class can method definition Only method declaration
27
Nested Interfaces
• An interface can be declared as a
• member of a class or
• another interface.
• Such an interface is called a member interface or a
nested interface.
• A nested interface can be declared as public, private, or
protected.
• Note : top-level interface, must either be declared as
public or use the default access level.
• Outside of the class or interface in which a nested
interface is declared, its name must be fully qualified.

28
• An example that demonstrates a nested interface
class A {
public interface NestedIF {
boolean isNotNegative(int x); }
}
class B implements A.NestedIF { // B implements the nested interface.
public boolean isNotNegative(int x)
{ return x < 0 ? false : true; }
}
class NestedIFDemo {
public static void main(String args[]) {
A.NestedIF nif = new B(); // use a nested interface reference
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
}}
29
Interface inside Interface
Syntax:

interface interface_1
{
-----
-----
interface interface_2
{
--------
--------
}
}
30
Example of nested Interface
interface Showable {
void show();
interface Messege {
void msg(); }
}
class Test implements Showable.Messege {
public void msg() {
System.out.println("This is Nested Interface"); }
public static void main(String args[]) {
Showable.Messege message=new Test();
message.msg();
}} 31
Accessing Interface Variable
• Interface can be used to declare a set of constants
that can be used in different classes.
• The constant values will be available to any class
that implements it.
• The values can be used in any method.
interface A
{
int m=10;
int n=50;
}

class B implements A
{
int x=m;
……
} 32
33
Packages: Putting Classes
Together
• One of the main features of OOP is its ability to reuse
the code already created.
• One way is to inheritance – limited to reusing the
classes within the program.

• What if we need to use classes from other programs?

• This can be accomplished in java by using “Packages”


• Similar to “class libraries” in other languages.

34
Packages in java
• Packages are java’s way of grouping a variety of classes
and/ or interfaces together.

• The grouping is usually done according to functionality.

• Packages act as containers for classes.

• Examples of packages:
lang, awt, util, applet, javax, swing, net, io, sql ,etc.

35
Advantages of packages
1. The classes contained in the package can be
easily reused.

2. Two classes in two different packages can have


the same name.

3. Package provide a way to hide classes thus


preventing other programs or packages from
accessing classes that are for internal use only.

4. Provide a way of separating “design” from


“coding”.
36
Different Types of Packages:
• There are two types of packages in Java:
• Built-in packages
• User-defined packages

37
Built-in packages
• They are also called as Java API Packages.
• Java API provides a large number of classes grouped
into different packages according to functionality.

38
Java API Packages
• Java.lang: lang stands for language.
• This package got primary classes and interfaces essential for
developing a basic Java program.
• It consists of wrapper classes , String, SttringBuffer,
StringBuilder classes to handle strings, thread class.
• Java.util: util stands for utility.
• This package contains useful classes and interfaces like Stack,
LinkedList, Hashtable, Vector, Arrays, Date and Time classes.
• Java.io: io stands for input and output.
• This package contains streams. A stream represents flow of
data from one place to another place. Streams are useful to
store data in the form of files and also to perform input-output
related tasks.

39
Java API Packages
• Java.awt: awt stands for abstract window toolkit.
• This helps to develop GUI(Graphical user Interfaces) with
colorful screens, paintings and images etc., can be developed.
It consists of , classes which are useful to provide action for
components like push buttons, radio buttons, menus etc.
• Java.net: net stands for network.
• Client-Server programming can be done by using this
package. Classes related to obtaining authentication for
network, client and server to establish communication
between them are also available in java.net package.
• Java.applet:
• applets are programs which come from a server into a client
and get executed on the client machine on a network. Applet
class of this package is useful to create and use applets.

40
Using System packages
• The package name java contains package awt, which contains
various classes required for implementing GUI.

java
awt
Color

Graphics
javajavajava

• Hierarchical representation
Images of java.awt package.

41
Using System Packages
• Classes stored in packages can be accessed in two
ways
1.Use the fully qualified class name of class that we
want to use. This is done by using package name
containing the class name using dot operator.
• Example :
import java.awt.Color
2.In many situations we might use class name in number
of places in the program or we may like to use many
classes of that package then-
• Example:
import java.awt.*
42
Naming Conventions
• Package names are written in lower case to avoid
conflict with the names of classes or interfaces.
• All class names begin with uppercase letters and
methods with lower case letters.

double y=java.lang.Math.sqrt(x);

Class name

Package Name Method name

43
User-Defined packages:
• Just like the built in packages shown earlier, the
users of the Java language can also create their own
packages.
• They are called user-defined packages.
• User-defined packages can also be imported into
other classes and used exactly in the same way as
the Built-in packages.

44
Creating Packages
• package packagename; //to create a package
• package packagename.subpackagename;
• //to create a sub package within a package.
e.g.: package pack;
• The first statement in the program must be first
statement while creating a package.
• While creating a package except instance
variables, declare all the members and the class
itself as public then only the public members are
available outside the package to other programs.

45
A program to create a package pack with Addition
class.
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{ d1 = a;
d2 = b;
}
public void sum()
{ System.out.println ("Sum of two given numbers is : " +
(d1+d2) );
}
} 46

You might also like