0% found this document useful (0 votes)
73 views41 pages

Abstract Classes and Interfaces in Java

Uploaded by

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

Abstract Classes and Interfaces in Java

Uploaded by

danevangadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Object Oriented Programming

(CSE 2202)

Lecture– Six
Abstract class ,Interface and Package

1
Outline ASTU

Content of the lecture


 Introduction to Abstract Class
 Introduction to interface
 Syntax and properties
 Implementing Abstract class and
interface with example
 Multiple inheritance in java
 Inner class
 Package
2
Abstract class ASTU

• An abstract class is one which


contains some defined methods
and some undefined
• Undefined methods are also known
as unimplemented or abstract
methods
• To make the method as abstract we
have to use a keyword called
abstract before the function
declaration
3
Contd. ASTU

 While using abstract classes:

 We cannot use abstract classes to instantiate objects


directly.
 The abstract method of an abstract class must be
defined in its subclass.
 We cannot declare abstract constructors or abstract
static methods.
 Abstract classes can have none, one or more abstract
methods and one or more non abstract methods
 A subclass of abstract class should be implements all
abstract methods
 An abstract class can have data member, abstract method,
method body, constructor and even main() method.

4
Contd. ASTU

Syntax for ABSTRACT CLASS:


abstract class <clsname>
{
Abstract return_type method_name (method
parameters if any);
};
• With respect to abstract class we cannot
create an object direct but we can create
indirectly.

5
Contd. ASTU

• An object abstract class is equal to an


object of class which extends abstract
class.
For Example:
class CC extends AC
{………;
………;
};
AC Ao=new AC (); //invalid
AC Ao=new CC ();
or
AC Ao;
Ao=new CC ();

6
Example ASTU

abstract class Bank{


abstract int getRateOfInterest();
}
class CBE extends Bank{
int getRateOfInterest(){return 7;}
}
class Awash extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new CBE();
[Link]("Rate of Interest is: "+[Link]()+" %");
b=new Awash();
[Link]("Rate of Interest is: "+[Link]()+" %");
}}

7
Example ASTU

abstract class Bike{


Bike(){[Link]("bike is created");}
abstract void run();
void changeGear(){[Link]("gear changed");}
}

class Honda extends Bike{


void run(){[Link]("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
[Link]();
[Link]();
}
}

8
Example ASTU

abstract class Shape{


abstract void draw();
}
//
In real scenario, implementation is provided by others i.e. unknown by end user

class Rectangle extends Shape{


void draw(){[Link]("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){[Link]("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method
[Link]();
}
}

9
Abstract class ASTU

• The abstract class can also be used


to provide some implementation of
the interface. In such case, the end
user may not be forced to override
all the methods of the interface.

10
Example ASTU

interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){[Link]("I am C");}
}

class M extends B{
public void a(){[Link]("I am a");}
public void b(){[Link]("I am b");}
public void d(){[Link]("I am d");}
}

class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

11
Interface ASTU

 Interface is a collection of public static final variables (constants) and

abstract methods.
 Interface is a collection of universal common reusable data members
and methods .
 A programmer uses an abstract class when there are some common
features shared by all the objects.
 A programmer writes an interface when all the features have different
implementations for different objects.
 Interfaces are written when the programmer wants to leave the
implementation to third party vendors.
 An interface is a specification of method prototypes.

 An interface contains zero or more abstract methods and all the


methods of interface are public, abstract by default.

12
Defining Interface ASTU

access-specifier interface interface_name


{
type final-varname1 = value;
type final-varname2 = value;
...
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
...
}
• Access can be public or default
• The methods which are declared have no
bodies(abstract). They end with a semicolon after
the parameter list.
• Each class that includes an interface must
implement all of the methods.
13
Rules of Interface ASTU

• It does not implement any methods


• A class that implement an interface
must implement all its methods
• Interface can not be instantiated
• Any method defined under the
interface become public & abstract
and any variable also become final
and static even if you are not
explicitly mention

14
Properties of interface
ASTU

 Interface is a keyword used for developing


universal user fined data type
 Each method in an interface is also implicitly
abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.
 All the data members of interface are implicitly
public static final.
 It does not contain any constructors.
 All methods in an interface are abstract.

15
interface ASTU

interface Shape
{ void area ();
void volume ();
double pi = 3.14;
}

class Circle implements Shape


{ double r;
Circle (double radius)
{ r = radius;
}
public void area ()
{ [Link]("Area of a circle is:" + pi*r*r );
}
public void volume ()
{ [Link]("Volume of a circle is:" + 2*pi*r);
}
} 16
interface ASTU

class Rectangle implements Shape


{ double l,b;
Rectangle (double length, double breadth)
{ l = length;
b = breadth;
}
public void area ()
{ [Link]("Area of a Rectangle is: " + l*b );
}
public void volume ()
{ [Link]("Volume of a Rectangle is:"+2*(l+b));
}
}
class InterfaceDemo
{ public static void main (String args[])
{ Circle ob1 = new Circle (10.2);
[Link] ();
[Link] ();
Rectangle ob2 = new Rectangle (12.0, 20.0);
[Link] ();
[Link] ();
}
}

17
Example 2 ASTU

Class intern extends student implement


interface employee
employee
{double st-salary=500;
{ double Income;
String descr();
public intern(String n, String d)
Double getsalry();
{ super(n,d);
}
Income=st-salary;
Class student { }
String name,dept; public double getsalary()
Public student(string n,string {return Income;}
d) Public string descr()
{name=n; dept=d;} {return “name:”+super.get_name()
String get_name(){return +“Dept :”+ super.get_dept() + ”Income ”
name;} +income}
String get_dept(){return }//end of class intern
dept;}
Public string descr() Class test {
{return “Stud Public static void main(String args[])
dept :”+dept;} { intern I1=new intern(“Selemon Getachew
}//end of class student ”,”IT”);
[Link]([Link]()); 18
Multiple inheritance in java ASTU

 Java does not support multiple inheritance. But it can be achieved by using

interfaces.

19
Interface vs. Abstract Class ASTU

Interface Abstract Class


• Methods can be declared • Methods can be declared
• No method bodies • Method bodies can be de-
• Constants can be de- fined
clared • Can have constructors
• Has no constructors • All types of variables can
• Multiple inheritance pos- be declared
sible • Multiple inheritance not
• Multiple “parent” inter- possible
faces • Always inherits from Ob-
ject
• Only one “parent” class
20
Inner/Nested class ASTU

class Outer { package OOP;


int outer_x = 100; class up
void test() { { private void showup()
Inner inner = new Inner(); {[Link]("Upper");}
[Link](); public class mid{
} private void showmid()
class Inner {// this is an inner class {[Link]("Middle");}
int y = 10; // y is local to Inner public class lower{
void display() { void showlow()
[Link]("display: outer_x { showup(); showmid();
="+ [Link]("Lower");}
outer_x); }
}} }
void showy() { }
[Link](y); // error, y not class testnest{
known here! public static void main(String []args)
}} {
class InnerClassDemo { up u1=new up();
public static void main(String args[]) [Link] m1=[Link] mid();
{ [Link] l1=[Link] lower();
Outer outer = new Outer(); [Link](); 21
Local Inner class ASTU

Example 1:
Example 2:
class city{
int x=10;
class localInner1{
public int get_x(){return x;}
private int data=30;//instance
}
variable
class parcel1
void display(){
{ int y;
class Local{
public city anon1()
int x=5;
{return new city()
void msg()
{int y=15; //variable of class
{[Link](data+x);}
city
}
public int get_x(){return
Local l=new Local();
x+y;}
[Link]();
};//end of class city
}
}//end of of method anon1
public static void main(String args[])
public static void main(String
{
args[])
localInner1 obj=new localInner1();
{ city c2=new city();
[Link]();
[Link](c2.get_x());
}
parcel1 p=new parcel1();
city c=p.anon1();
} 22
Static Nested Class ASTU

• A static class i.e. created inside a class is called static nested class
in java. It cannot access non-static data members and methods. It
can be accessed by outer class name.
– It can access static data members of outer class including private.
– Static nested class cannot access non-static (instance) data member or
method.

class TestOuter1{
static int data=30;
static class Inner{
void msg(){[Link]("data is "+data);}
}
public static void main(String args[]){
[Link] obj=new [Link]();
[Link]();
}
}

23
Package ASTU

Package is a collection of related classes ,interface and sub package .

If any class or interface is common for many number of java programmers ,such

type classes and interface we place in the packages or in other words all the
classes and interface of a package are common for all the java programmers.
A package represents a directory that contains related group of

classes and interfaces.


In java packages are classified into 3 types

1.) pre defined packages

2.) user/programmer defined packages

3.) Third party packages

24
Package ASTU

Pre defined packages


Pre defined packages are those developed by sun micro
system and supplied as a part of jdk to deal with common
requirements .
 [Link].*;
 [Link].*;
 [Link].*;

User defined packages.


Are those which are developed by java programmers and are supplied as a
part of their project to deal with common requirements

Third party packages.


are those developed by third party software vendors and released to real
industry as part of products .
Example [Link].

25
Package ASTU

• Syntax for creating a package:


package packagename;
Ex: package pack;
• The package creation statement must be the first
statement in the program while creating a package.
• And, declare all the members and the class itself as
public
– then only the public members are available outside the
package to other programs.

• When the package statement is omitted, class names


are put into the default package which has no name.
26
Example – Creating a Package ASTU

//creating a package
package pack;
public class Addition
{ private double d1,d2;
public Addition(double a,double b)
{ d1 = a;
d2 = b;
}
public void sum()
{ [Link] ("Sum is : " + (d1+d2) );
}
}

27
package ASTU

Guidelines for placing classes and


interface in the package
For placing classes and interface in the packages ,sun micro system
developers has prescribed the following guide lines .

1.) choose an appropriate packages name for placing class and


interface for common classes and interface.
2.) choose an appropriate class name and interface name and ensure
whose modifier must be public .
3.) the modifier of the method of the class/interface which present in
the packages must be public .
4.) the modifier of the constructor of the class which present in the
packages must be public ( this rule is not applicable in the case of
interface.

28
Importing of Packages ASTU

• Since classes within packages must be fully-


qualified with their package names, it would be
tedious to always type long dot-separated
names.
• The import statement allows to use classes or
whole packages directly.
• Importing of a concrete class:
import [Link];

• Importing of all classes within a package:


import myPackage1.myPackage2.*;

• The import statement occurs immediately after


the package statement and before the class
statement
29
Example – Importing a Package ASTU

//Using the package pack


import [Link];
class Use
{
public static void main(String args[])
{ Addition ob1 = new Addition(10,20);
[Link]();
}
}

30
Example- another class ASTU

//Adding one more class to package pack:


package pack;
public class Subtraction
{ private double d1,d2;
public Subtraction(double a, double b)
{ d1 = a;
d2 = b;
}
public void difference()
{ [Link]("Subtraction: " + (d1 - d2));
}
}

31
Example – Importing all classes ASTU

//To import all the classes and interfaces in a


class using import pack.*;
import pack.*;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10.5,20.6);
[Link]();
Subtraction ob2 = new Subtraction(30.2,40.11);
[Link]();
}
}

32
Fully qualified name approach ASTU

• It is one of the alternative approach for referring


the classes and interface of the packages instead
of import statement (keyword).
• This approach can refer either a class or interface
but not possible to refer all the classes and
interface of the packages.
Syntax pack1.pack2.class_name/interface
Example
Class test extends [Link]
{

33
Access Protection ASTU

• Specifies the scope of the data members, class and


methods.
– private members of the class are available with in the
class only. The scope of private members of the class is
“CLASS SCOPE”.
– public members of the class are available anywhere . The
scope of public members of the class is "GLOBAL SCOPE".
– default members of the class are available with in the
class, outside the class and in its sub class of same
package. It is not available outside the package. So the
scope of default members of the class is "PACKAGE
SCOPE".
– protected members of the class are available
with in the class, outside the class and in its sub
class of same package and also available to
subclasses in different package also.
34
Cont.… ASTU

35
private access modifier ASTU

class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}

36
Default access modifier ASTU

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible
only within package.

package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
37
protected access modifier ASTU

• The protected access modifier is


accessible within package and
outside the package but through
inheritance only.
• The protected access modifier can be
applied on the data member, method
and constructor. It can't be applied
on the class

38
Protected ASTU

//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}

39
public access modifier ASTU

• The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}

40
ASTU

Thank You!!!
Q?

41

You might also like