0% found this document useful (0 votes)
33 views

Unit No.3-JPR

This document discusses inheritance, interfaces, and packages in Java programming. It covers the concepts of inheritance including single, multilevel, and hierarchical inheritance. It provides examples to demonstrate single-level, multilevel, and hierarchical inheritance. It also discusses method overloading as an example of static polymorphism determined at compile time, and method overriding which allows subclasses to provide their own implementation of an inherited method from the parent class.

Uploaded by

shubhamkanlod16
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)
33 views

Unit No.3-JPR

This document discusses inheritance, interfaces, and packages in Java programming. It covers the concepts of inheritance including single, multilevel, and hierarchical inheritance. It provides examples to demonstrate single-level, multilevel, and hierarchical inheritance. It also discusses method overloading as an example of static polymorphism determined at compile time, and method overriding which allows subclasses to provide their own implementation of an inherited method from the parent class.

Uploaded by

shubhamkanlod16
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/ 43

Java Programming (22412)

Unit No.3
Inheritance, Interface and Package

 CO b. Apply concept of inheritance for code reusability.


 CO c. Develop programs using multithreading.

3.1 Inheritance:

Concept of Inheritance

 Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of 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 parent class, and you can add new methods and fields also.
 Inheritance represents the IS-A relationship, also known as parent-child relationship.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

Types of inheritance in java

There are three types of inheritance in java: single, multilevel and hierarchical.

Sou.Venutai Chavan Polytechnic,Pune. 1


Java Programming (22412)

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

3.2
Single-level Inheritance

class A

public void methodA()

System.out.println("Base class method");

class B extends A

public void methodB()

System.out.println("Child class method");

public static void main(String args[])

Sou.Venutai Chavan Polytechnic,Pune. 2


Java Programming (22412)

B obj = new B();

obj.methodA(); //calling super class method

obj.methodB(); //calling local method

Output –

Base class method

Child class method

Multilevel Inheritance

class X

public void methodX()

System.out.println("class X method");

class Y extends X

public void methodY()

System.out.println("class Y method");

class Z extends Y

Sou.Venutai Chavan Polytechnic,Pune. 3


Java Programming (22412)

public void methodZ()

System.out.println("class Z method");

public static void main(String args[])

Z obj = new Z();

obj.methodX(); //calling grand parent class method

obj.methodY(); //calling parent class method

obj.methodZ(); //calling local method

Output –

class X method

class Y method

class Z method

Hierarchical Inheritance

class A

Sou.Venutai Chavan Polytechnic,Pune. 4


Java Programming (22412)

public void methodA()

System.out.println("method of Class A");

class B extends A

public void methodB()

System.out.println("method of Class B");

class C extends A

public void methodC()

System.out.println("method of Class C");

class D extends A

Sou.Venutai Chavan Polytechnic,Pune. 5


Java Programming (22412)

public void methodD()

System.out.println("method of Class D");

class MIDemo

public void methodB()

System.out.println("method of Class B");

public static void main(String args[])

B obj1 = new B();

C obj2 = new C();

D obj3 = new D();

obj1.methodA();

obj2.methodA();

obj3.methodA();

Output –

method of Class A
method of Class A
method of Class A

Sou.Venutai Chavan Polytechnic,Pune. 6


Java Programming (22412)

Overloading & Overriding

Method Overloading –

 Method Overloading is a feature that allows a class to have two or more methods having
same name, if their argument lists are different.

 Method overloading is also known as Static Polymorphism.


1. Static Polymorphism is also known as compile time binding or early binding.

2. Static binding happens at compile time. Method overloading is an example of static


binding where binding of method call to its definition happens at Compile time.

Example – Overloading – Different Number of parameters in argument list

class overDemo

public void disp(String s)

System.out.println(s);

public void disp(String s, int num)

System.out.println(s + " "+num);

class OverTest

Sou.Venutai Chavan Polytechnic,Pune. 7


Java Programming (22412)

public static void main(String args[])

overDemo obj = new overDemo();

obj.disp("Hello");

obj.disp("Welcome",10);

Output –

Hello

Welcome 10

Example - Overloading – Difference in data type of arguments

class overDemo

public void disp(String s)

System.out.println(s);

public void disp(int s)

System.out.println(s);

class OverTest

public static void main(String args[])

Sou.Venutai Chavan Polytechnic,Pune. 8


Java Programming (22412)

overDemo obj = new overDemo();

obj.disp("Hello");

obj.disp(100);

Output –

Hello

100

Method Overriding

 Declaring a method in subclass which is already present in parent class is known as


method overriding
 Advantage of method overriding - The main advantage of method overriding is that the
class can give its own specific implementation to a inherited method without even
modifying the parent class(base class).

One of the simplest example – Here Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the eat() method or in
other words it is overriding the method eat().

class Human

public void eat()

System.out.println("Human is eating");

class Boy extends Human

Sou.Venutai Chavan Polytechnic,Pune. 9


Java Programming (22412)

public void eat()

System.out.println("Boy is eating");

public static void main( String args[])

Boy obj = new Boy();

obj.eat();

Overloading & Overriding

Method Overloading –

 Method Overloading is a feature that allows a class to have two or more methods having
same name, if their argument lists are different.

 Method overloading is also known as Static Polymorphism.


1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static
binding where binding of method call to its definition happens at Compile time.

Example – Overloading – Different Number of parameters in argument list

class overDemo

public void disp(String s)

System.out.println(s);

public void disp(String s, int num)

Sou.Venutai Chavan Polytechnic,Pune. 10


Java Programming (22412)

System.out.println(s + " "+num);

class OverTest

public static void main(String args[])

overDemo obj = new overDemo();

obj.disp("Hello");

obj.disp("Welcome",10);

Output –

Hello

Welcome 10

Example - Overloading – Difference in data type of arguments

class overDemo

public void disp(String s)

System.out.println(s);

public void disp(int s)

Sou.Venutai Chavan Polytechnic,Pune. 11


Java Programming (22412)

System.out.println(s);

class OverTest

public static void main(String args[])

overDemo obj = new overDemo();

obj.disp("Hello");

obj.disp(100);

Output –

Hello

100

 Method Overriding
 Declaring a method in subclass which is already present in parent class is known as
method overriding
 Advantage of method overriding - The main advantage of method overriding is that the
class can give its own specific implementation to a inherited method without even
modifying the parent class(base class).

One of the simplest example – Here Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the eat() method or in
other words it is overriding the method eat().

class Human

public void eat()

Sou.Venutai Chavan Polytechnic,Pune. 12


Java Programming (22412)

System.out.println("Human is eating");

class Boy extends Human

public void eat()

System.out.println("Boy is eating");

public static void main( String args[])

Boy obj = new Boy();

obj.eat();

Output - Boy is eating

Boy is eating

Dynamic method dispatch Runtime Polymorphism or

Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at


runtime. This is how java implements runtime polymorphism. When an overridden method is
called by a reference, java determines which version of that method to execute based on the type
of object it refer to. In simple words the type of object which it referred determines which
version of overridden method will be called.

Sou.Venutai Chavan Polytechnic,Pune. 13


Java Programming (22412)

class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}

Class Cricket extends Game


{
public void type()
{ System.out.println("outdoor game"); }

public static void main(String[] args)


{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm=ck; //gm refers to Cricket object
gm.type(); //calls Cricket's version of type
}
}

Output

Indoor & outdoor


Outdoor game
Outdoor game

Sou.Venutai Chavan Polytechnic,Pune. 14


Java Programming (22412)

Notice the last output. This is because of gm = ck; Now gm.type() will call Cricket version of
type method. Because here gm refers to cricket object.

Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload static method in java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

Sou.Venutai Chavan Polytechnic,Pune. 15


Java Programming (22412)

class A{}

class B extends A{}

A a=new B();//upcasting

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

class Bike{

void run(){System.out.println("running");}

class Splender extends Bike{

void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){

Bike b = new Splender();//upcasting

b.run();

Sou.Venutai Chavan Polytechnic,Pune. 16


Java Programming (22412)

Output:running safely with 60km.

Bank b1=new SBI();

Bank b2=new ICICI();

Bank b3=new AXIS();

System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());

System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());

System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());

Finalize()

class a

String n;

a()

Sou.Venutai Chavan Polytechnic,Pune. 17


Java Programming (22412)

n="svcp";

System.out.println(n);

protected void finalize()

System.out.println("finalized....");

public static void main(String args[])

a obj=new a();

obj.finalize();

1) final variable

final variables are nothing but constants. We cannot change the value of a final variable once it is
initialized.

class Demo{
final int MAX_VALUE=99;
void myMethod()
{
//MAX_VALUE=101;
}

Sou.Venutai Chavan Polytechnic,Pune. 18


Java Programming (22412)

public static void main(String args[])


{
Demo obj=new Demo();
obj.myMethod();
}
}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:


The final field Demo.MAX_VALUE cannot be assigned
at beginnersbook.com.Demo.myMethod(Details.java:6)
at beginnersbook.com.Demo.main(Details.java:10)
We got a compilation error in the above program because we tried to change the value of a final
variable “MAX_VALUE”.

Note: It is considered as a good practice to have constant names in UPPER CASE(CAPS).

Blank final variable

A final variable that is not initialized at the time of declaration is known as blank final variable.
We must initialize the blank final variable in constructor of the class otherwise it will throw a
compilation error (Error: variable MAX_VALUE might not have been initialized).

This is how a blank final variable is used in a class:

class Demo{
//Blank final variable
final int MAX_VALUE;
Demo(){
//It must be initialized in constructor
MAX_VALUE=100;
}

Sou.Venutai Chavan Polytechnic,Pune. 19


Java Programming (22412)

void myMethod(){
System.out.println(MAX_VALUE);
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}
Output:

100

Use of blank final variable- Lets say we have a Student class which is having a field called Roll
No. Since Roll No should not be changed once the student is registered, we can declare it as a
final variable in a class but we cannot initialize roll no in advance for all the students(otherwise
all students would be having same roll no). In such case we can declare roll no variable as blank
final and we initialize this value during object creation like this:

class StudentData{
//Blank final variable
final int ROLL_NO;
StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();

Sou.Venutai Chavan Polytechnic,Pune. 20


Java Programming (22412)

}
}
Output:

Roll no is:1234
More about blank final variable at StackOverflow and Wiki.

Uninitialized static final variable

A static final variable that is not initialized during declaration can only be initialized in static
block. Example:

class Example{
//static blank final variable
static final int ROLL_NO;
static{
ROLL_NO=1230;
}
public static void main(String args[]){
System.out.println(Example.ROLL_NO);
}
}
Output:

1230

2) final method

A final method cannot be overridden. Which means even though a sub class can call the final
method of parent class without any issues but it cannot override it.

Example:

Sou.Venutai Chavan Polytechnic,Pune. 21


Java Programming (22412)

class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ{


void demo(){
System.out.println("ABC Class Method");
}

public static void main(String args[]){


ABC obj= new ABC();
obj.demo();
}
}
The above program would throw a compilation error, however we can use the parent class final
method in sub class without any issues. Lets have a look at this code: This program would run
fine as we are not overriding the final method. That shows that final methods are inherited but
they are not eligible for overriding.

class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ{


public static void main(String args[]){
ABC obj= new ABC();
obj.demo();

Sou.Venutai Chavan Polytechnic,Pune. 22


Java Programming (22412)

}
}
Output:

XYZ Class Method

3) final class

We cannot extend a final class. Consider the below example:

final class XYZ{


}

class ABC extends XYZ{


void demo(){
System.out.println("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
Output:

The type ABC cannot subclass the final class XYZ

Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.

Sou.Venutai Chavan Polytechnic,Pune. 23


Java Programming (22412)

6) A final class not be inherited.


7) If method parameters are declared final then the value of these parameters cannot be changed.
8) It is a good practice to name final variable in all CAPS.
9) final, finally and finalize are three different terms. finally is used in exception handling and
finalize is a method that is called by JVM during garbage collection.

Super
 super keyword is used for calling the parent class method/constructor.
 super Usage:

1) super.<variable_name> refers to the variable of variable of parent class.

2) super() invokes the constructor of immediate parent class.


3) super.<method_name> refers to the method of parent class.
 Super() is added in each class constructor automatically by compiler.

Example – calling variable of parent class

class parent

String s="Parent";

class child extends parent

String s="Child";

void print()

System.out.println(s);

System.out.println(super.s);

public static void main(String args[])

Sou.Venutai Chavan Polytechnic,Pune. 24


Java Programming (22412)

child obj = new child();

obj.print();

Output –

Child

Parent

Example – calling constructor of parent class

class Parentclass

Parentclass()

System.out.println("Constructor of Superclass");

class Subclass extends Parentclass

Subclass()

super();

System.out.println("Constructor of Subclass");

void display(){

System.out.println("Hello");

Sou.Venutai Chavan Polytechnic,Pune. 25


Java Programming (22412)

public static void main(String args[]){

Subclass obj= new Subclass();

obj.display();

Output –

Constructor of Superclass

Constructor of Subclass

Hello

Example – calling method of parent class

class Human

public void eat()

System.out.println("Human is eating");

class Boy extends Human

public void eat()

super.eat();

System.out.println("Boy is eating");

public static void main( String args[]) {

Sou.Venutai Chavan Polytechnic,Pune. 26


Java Programming (22412)

Boy obj = new Boy();

obj.eat();

Output –

Human is eating

Boy is eating

Static Keyword

The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block

Advantages – it saves memory

Static Variable

If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.

Program –

Code without static keyword

class Counter{
int count=0;//will get memory when instance is created

Counter(){
count++;

Sou.Venutai Chavan Polytechnic,Pune. 27


Java Programming (22412)

System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

}
}

Output:1
1
1

Code with static keyword

class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}
Output:1
2
3

Example -

class staticdemo

int rollno;

Sou.Venutai Chavan Polytechnic,Pune. 28


Java Programming (22412)

String name;

static String college ="Svcp”;

staticdemo (int r,String n)

rollno = r;

name = n;

void display ()

System.out.println(rollno+" "+name+" "+college);

public static void main(String args[]){

staticdemo s1= new staticdemo (111,"Karan");

staticdemo s2 = new staticdemo (222,"Aryan");

s1.display();

s2.display();

Output: 111 Karan Svcp


222 Aryan Svcp

Static Method –

If you apply static keyword with any method, it is known as static method.

 It is a method which belongs to the class and not to the object(instance)


 A static method can access only static data. It cannot access non-static data (instance
variables)

Sou.Venutai Chavan Polytechnic,Pune. 29


Java Programming (22412)

 A static method can call only other static methods and cannot call a non-static method
from it.
 A static method can be accessed directly by the class name and doesn’t need any object
 Syntax : <class-name>.<method-name>
 A static method cannot refer to “this” or “super” keywords in anyway
 The static method cannot use non static data member or call non-static method directly.

class smethod

int rollno;

String name;

static String college = "STES";

static void change()

college = "SVCP";

smethod(int r, String n)

rollno = r;

name = n;

void display ()

System.out.println(rollno+" "+name+" "+college);

Sou.Venutai Chavan Polytechnic,Pune. 30


Java Programming (22412)

public static void main(String args[])

smethod.change();

smethod s1 = new smethod (111,"Karan");

smethod s2 = new smethod (222,"Aryan");

smethod s3 = new smethod (333,"Sonu");

s1.display();

s2.display();

s3.display();

Output:111 Karan SVCP


222 Aryan SVCP
333 Sonu SVCP

Static Block

o Is used to initialize the static data member.


o It is executed before main method at the time of classloading.

class sblock{

static

System.out.println("static block is invoked");

public static void main(String args[])

System.out.println("Hello main");

Sou.Venutai Chavan Polytechnic,Pune. 31


Java Programming (22412)

Output: static block is invoked


Hello main

Important Points –

 It is a variable which belongs to the class and not to object(instance)


 Static variables are initialized only once , at the start of the execution . These variables will
be initialized first, before the initialization of any instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn’t need any object
 Syntax : <class-name>.<variable-name>

Abstract Classes and Methods

A class that is declared using “abstract” keyword is known as abstract class. It may or may not
include abstract methods which means in abstract class you can have concrete methods (methods
with body) as well along with abstract methods ( without an implementation, without braces, and
followed by a semicolon). An abstract class can not be instantiated (you are not allowed to
create object of Abstract class).

Abstract class declaration

Syntax –

abstract class class_name

// Declaration using abstract keyword


abstract class AbstractDemo{
// Concrete method: body and braces

Sou.Venutai Chavan Polytechnic,Pune. 32


Java Programming (22412)

public void myMethod(){


//Statements here
}

// Abstract method: without body and braces


abstract public void anotherMethod();
}
Since abstract class allows concrete methods as well, it does not provide 100% abstraction. You
can say that it provides partial abstraction. Interfaces are used for 100% abstraction
(full abstraction)

Remember two rules:

1) If the class is having few abstract methods and few concrete methods: declare it as
abstract class.
2) If the class is having only abstract methods: declare it as interface.

Key Points:

1. An abstract class has no use until unless it is extended by some other class.
2. If you declare an abstract method (discussed below) in a class then you must declare the
class abstract as well. you can’t have abstract method in a non-abstract class. It’s vice
versa is not always true: If a class is not having any abstract method then also it can be
marked as abstract.
3. Abstract class can have non-abstract method (concrete) as well.

Abstract methods

Well, we already discussed about abstract methods in the above section. Lets take few examples
to understand it better.

Syntax:

Sou.Venutai Chavan Polytechnic,Pune. 33


Java Programming (22412)

public abstract void display();


Points to remember about abstract method:

1) Abstract method has no body.

2) Always end the declaration with a semicolon(;).

3) It must be overridden. An abstract class must be extended and in a same way abstract
method must be overridden.

4) Abstract method must be in a abstract class.

Note: The class which is extending abstract class must override (or implement) all the abstract
methods.

Example of Abstract class and method

abstract class Demo1{


public void disp1(){
System.out.println("Concrete method of abstract class");
}
abstract public void disp2();
}

class Demo2 extends Demo1{


/* I have given the body to abstract method of Demo1 class
It is must if you don't declare abstract method of super class
compiler would throw an error*/
public void disp2()
{
System.out.println("I'm overriding abstract method");
}

Sou.Venutai Chavan Polytechnic,Pune. 34


Java Programming (22412)

public static void main(String args[]){


Demo2 obj = new Demo2();
obj.disp2();
}
}
Output:

I'm overriding abstract method

3.3 Interface
Interface is a pure abstract class. They are syntactically similar to classes, but you cannot create
instance of an Interface and their methods are declared without any body. Interface is used to
achieve complete abstraction in Java. When you create an interface it defines what a class can
do without saying anything about how the class will do it.

Syntax :

interface interface_name { }

Example of Interface

interface Moveable

int AVERAGE-SPEED=40;

void move();

Rules for using Interface

 Methods inside Interface must not be static, final, native or strictfp.


 All variables declared inside interface are implicitly public static final variables(constants).
 All methods declared inside Java Interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword.

Sou.Venutai Chavan Polytechnic,Pune. 35


Java Programming (22412)

 Interface can extend one or more other interface.


 Interface cannot implement a class.
 Interface can be nested inside another interface.

Example of Interface implementation

interface Moveable

int AVG-SPEED = 40;

void move();

class Vehicle implements Moveable

public void move()

System .out. print in ("Average speed is"+AVG-SPEED");

public static void main (String[] arg)

Vehicle vc = new Vehicle();

vc.move();

Output :

Average speed is 40.

Sou.Venutai Chavan Polytechnic,Pune. 36


Java Programming (22412)

Interfaces supports Multiple Inheritance

Though classes in java doesn't suppost multiple inheritance, but a class can implement more than
one interface.

interface Moveable

boolean isMoveable();

interface Rollable

boolean isRollable

class Tyre implements Moveable, Rollable

int width;

boolean isMoveable()

return true;

boolean isRollable()

Sou.Venutai Chavan Polytechnic,Pune. 37


Java Programming (22412)

return true;

public static void main(String args[])

Tyre tr=new Tyre();

System.out.println(tr.isMoveable());

System.out.println(tr.isRollable());

Output :

true

true

Interface extends other Interface

Classes implements interfaces, but an interface extends other interface.

interface NewsPaper

news();

interface Magazine extends NewsPaper

colorful();

Sou.Venutai Chavan Polytechnic,Pune. 38


Java Programming (22412)

Abstract class Interface

Abstract class is a class which contain one Interface is a Java Object containing method
or more abstract methods, which has to be declaration but no implementation. The classes
implemented by its sub classes. which implement the Interfaces must provide the
method definition for all the methods.

Abstract class is a Class prefix with an Interface is a pure abstract class which starts with
abstract keyword followed by Class interface keyword.
definition.

Abstract class can also contain concrete Whereas, Interface contains all abstract methods
methods. and final variable declarations.

Abstract classes are useful in a situation Interfaces are useful in a situation that all
that Some general methods should be properties should be implemented.
implemented and specialization behavior
should be implemented by child classes.

3.4 Packages
Package are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of classes,
interface, enumeration and sub-package. Using package it becomes easier to locate the related
classes.

Package are categorized into two forms

 Built-in Package:-Existing Java package for example java.lang, java.util etc.

Sou.Venutai Chavan Polytechnic,Pune. 39


Java Programming (22412)

 User-defined-package:- Java package created by user to categorized classes and interfa

The classes that are included in these packages are:


 java.lang – Language support classes such as System, Thread, Exception etc.
 java.util – Utility classes such as Vector, Arrays, LinkedList, Stack etc.
 java.io – Input output support classes such as BufferedReader, InputStream
 java.awt – Classes using GUI such as Window, Frame, Panel etc.
 java.applet – Classes for creating and implementing applets.

Creating a package

Creating a package in java is quite easy. Simply include a package command followed by name
of the package as the first statement in java source file.

package mypack;

public class employee

...statement;

The above statement create a package called mypack.

Java uses file system directory to store package. For example the .class for any classes you to
define to be part of mypack package must be stored in a directory called mypack

Sou.Venutai Chavan Polytechnic,Pune. 40


Java Programming (22412)

Example of package creation

package mypack

class Book

String bookname;

String author;

Book(String b, String c)

this.bookname = b;

this.author = c;

public void show()

System.out.println(bookname+" "+ author);

class test

public static void main(String[] args)

Book bk = new Book("java","Herbert");

bk.show();

Sou.Venutai Chavan Polytechnic,Pune. 41


Java Programming (22412)

To run this program :

 create a directory under your current working development directory(i.e. JDK directory),
name it as mypack.
 compile the source file
 Put the class file into the directory you have created.
 Execute the program from development directory.

Uses of java package

Package is a way to organize files in java, it is used when a project consists of multiple modules.
It also helps resolve naming conflicts. Package's access level also allows you to protect data from
being used by the non-authorized classes.

import keyword

import keyword is used to import built-in and user-defined packages into your java source file.
So that your class can refer to a class that is in another package by directly using its name.

There are 3 different ways to refer to class that is present in different package

1. Using fully qualified name (But this is not a good practice.)

Example :

class MyDate extends java.util.Date

//statement;

2. import the only class you want to use.

Example :

import java.util.Date;

Sou.Venutai Chavan Polytechnic,Pune. 42


Java Programming (22412)

class MyDate extends Date

//statement.

3. import all the classes from the particular package

Example :

import java.util.*;

class MyDate extends Date

//statement;

Access Specifiers

 private: accessible only in the class


 no modifier: so-called “package” access — accessible only in the same package
 protected: accessible (inherited) by subclasses, and accessible by code in same package
 public: accessible anywhere the class is accessible, and inherited by subclasses

Sou.Venutai Chavan Polytechnic,Pune. 43

You might also like