Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

UNIT – III

Inheritance: Inheritance, The keyword ‘super’, The Protected Specifier, Types


ofInheritance Polymorphism: Polymorphism with Variables, Polymorphism using
Methods,Polymorphism with Static Methods, Polymorphism with Private Methods,
Polymorphism with Final Methods,final Class
Type Casting: Types of Data Types, Casting Primitive Data Types, Casting Referenced
DataTypes, The Object Class
Abstract Classes: Abstract Method and Abstract Class
Interfaces: Interface, Multiple Inheritance using Interfaces
Packages: Package, Different Types of Packages, The JAR Files, Interfaces in a
Package,Creating Sub Package in a Package, Access Specifiers in Java,
Creating APIDocument

INHERITANCE: -
Reusability is another aspect of OOP paradigm. It is always nice if we could
reuse
something that already exists rather than creating the same all over again. Java supports this
concept. Javaclasses can be reused in several ways. This is basically done by creating new
classes, reusing the properties of existing ones. The mechanism of deriving a new class from
an old one is called inheritance. The old class is known as the base class or super class or
parent class and the new one is called the subclass or derived class or child class.

The inheritance allows subclasses to inherit all thevariables and methods of their parent
classes. Inheritance may take different forms:
1. Single inheritance (only one super class)
2. Multiple inheritance (several super classes)
3. Hierarchical inheritance (one super class, many subclasses)
4. Multilevel inheritance (derived from a derived class)
These forms of inheritance are shown below.

A A B A A

B
C B C D
B C
(a) Single inheritance (b) Multilevel inheritance

(c) Multilevel inheritance (d) Hierarchical


inheritance

Note: -Java does not directly implement multiple inheritance. However, this concept is
implementedusing a secondary inheritance path in the form of interfaces.
1. Single Inheritance: -
Deriving the properties from a single class to other single class is known
as singleinheritance. Here the single class is known as ‘base class’ and other single class is ‘sub
class’.
A subclass is defined as
follows:Syntax :-
class subclassname extends superclasses
{
variables
declaration;
methods
declaration;
}

The keyword extends signifies that the properties of the superclassname are
extended to the subclassname. The subclass will now contain its own variables and
methods as well as those of thesuperclass. The following program illustrates the single
inheritance.

Ex:
class Room
{
int length; int
breadth;
Room(int x,int y)
{
length=x; breadth=y;
}
int area()
{
return (length*breadth);
}
}

class BedRoom extends Room //Inheriting Room


{
int height;
BedRoom(int x,int y,int z)
{
super(x,y); //pass values to superclass

height=z;
}
int volume( )
{
Return (length*breadth*height);
}
}

class inherTest
{
Public static void main(String args[])
{
BedRoom room1=new BedRoom(14,12,10);
int area1=room1.area(); //superclass method
int volume1=room1.volume(); //baseclass
methodSystem.out.println(“Area1=”+area1);
System.out.println(“Volume=”+volume);
}
}
Output:
Area1=168
Volume=168
0

The program defines a class Room and extends it to another class BedRoom. Note
that the classBedRoom defines its own data members and methods. The subclass BedRoom
now includes three instance variables,namely, length, breadth and height and two methods.,
area and volume.
The constructor in the derived class uses the super keyword to pass values that are required
by the baseconstructor. The statement
BedRoom room1=new BedRoom(14,12,10);
calls first the BedRoom constructor method, which in turn calls the Room constructor
method by usingthe super keyword.
Finally, the object room1 of the subclass BedRoom calls the method area defined in the
super class aswell as the method volume defined in the subclass itself.

2. Multilevel Inheritance: -
A common requirement in object-oriented programming is the
use of aderived class as a super class. This concept allows us to build a chain of classes
as shown below:

The class A serves as a base class for the derived class B which in turn serves as a
base classfor the derived class C. The chain ABC is known as inheritance path.

A derived class with multilevel base classes is declared as follows.

Syntax:
class A
{
. . . .. . . .
}

class B extends A //first level


{
. . . .. . . .
}

class C extends B //second level


{
....
....
}

Ex:

When there is a chain of inheritance, it is known asmultilevel inheritance . As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
} Output:
class BabyDog extends Dog{ weeping…
void weep(){System.out.println("weeping...");} barking…
} eating…
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat(); }}
3. Hierarchical Inheritance:-
Many programming problems can be cast into a hierarchy where
certain
features of one level are shared by many others below the level. As an example, following
figure shows ahierarchical classification of accounts in a commercial bank. This is possible
because all the accounts possess certain common features.

Syntax:

class Subclassname1 extends Superclassname

// variables and methods

class Subclassname2 extends Superclassname

// variables and methods


}

The “extends” meaning is to increase the functionality. The extends keyword indicates inheritance;

that is, we are making a new class that derives from an existing class.

Ex:

When two or more classes inherits a single class, it is known ashierarchical inheritance . In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
} Output:
class Cat extends Animal{ meowing…
void meow(){System.out.println("meowing...");} eating…
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}
Polymorphism in Java:

The word polymorphism means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form.
Real-life Illustration: Polymorphism
A person at the same time can have different characteristics. Like a man at the same time is a
father, a husband, an employee. So the same person possesses different behavior in different
situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism
allows you to define one interface and have multiple implementations. The word “poly” means
many and “morphs” means forms, So it means many forms.
Types of polymorphism:

In Java polymorphism is mainly divided into two types:


 Compile-time Polymorphism
 Runtime Polymorphism

Type 1: Compile-time polymorphism

It is also known as static polymorphism. This type of polymorphism is achieved by function


overloading or operator overloading.
Methods Overloading: -

Java supports to create methods that have the same name but different
parameter lists and different definitions. This is called “Method over-loading”.

Method over-loading is used when objects are required to perform similar tasks but using
different inputparameters. When we call a method in an object, java matches up the method
name first and then the number and type definitions to execute this process is also known as
“Polymorphism”.

To create an over-loaded method, all we have to do is to provide several different method


definitions in the class, all with the same name but with different parameters lists. The
difference may either be in thenumber or type of arguments that is each parameter-list should
be unique.

Example Program:

-class Room
{
float length;
float breadth;
Room (float x, float y)
{
length = x;
breadth = y;
}

Room (float x)
{
length = breadth = x;
}
float area( )
{
return (length * breadth);
}
}

class MethodOverloading
{
public static void main (String args[ ])
{
Room room1 = new Room
(25.0f,15.0f);float roomarea=
room1.area( );
Room room2 = new
Room(20.0f);roomarea =
room2.area( );
System.out.println(roomarea);
}
}
Type 2: Runtime polymorphism

Method Overriding:

It is also known as Dynamic Method Dispatch. It is a process in which a function call to the
overridden method is resolved at Runtime. This type of polymorphism is achieved by Method
Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for
one of the member functions of the base class. That base function is said to be overridden.

Example Program:

class Super

Super(int x)
{
this.x = x;
}
void display ( )
{
System.out.println(“Super x=”+ x);
}
}
class Sub extend Super
{
int y;
Sub(int x, int y)
{
super(x);
this.y = y;
}
void display ( )
{
System.out.println(“Super x=”+ x);
System.out.println(“Sub y=”+ y);
}
}
class OverrideTest
{
public static void main (String args[ ])
{
Sub obj = new Sub (100,
200);Obj.display ( );
}
}
Static Members:-

A class is basically contains two sections. One declares variables and the other
declaresmethods. These variables and methods are called “instance variables” and “instance
methods”. This isbecause every time the class is instantiated a new copy of them is created.
There are accessed using the object wit dot ( .) operator.

We want to define a member that is common to all the objects and accessed
without a particular object. This is the member belongs to the class has a whole rather than,
the object created fromthe class. Such members are called “class static members”, since
these members are associated with theclass itself rather than individual objects, the static
variables and static methods are often referred to as “class variables” and “class methods” in
order to distinguish them from their instance variables and instance methods.

Declaration of static variables and methods:

Syntax:- static datatype Variable_Name;

static datatype Method_Name (orguments list);

Static variables are used when we want to have a variable common to all instances of a class.
One of the most common examples is to have a variable that could keep a count of how many
objects of a class havebeen created. Java creates only one copy for a static variable which can
be used even if the class is never actually instantiated.

Example Program:

-class

MathOperation
{
static float mul( folat x, float y)
{
return x * y;
}
static float divide( folat x, float y)
{
return x / y;
}
}
class MathApplication
{
public static void main (String args[ ])
{
float a = MathOperation.mul(4.0f,
5.0f); float b =
MathOperation.divide( a , 2.0f);

System.out.println(“Multipication =”+
a);System.out.println(“Division =”+ b);
}
}
Final Classes: -

A final class can’t be sub-classed. This is done for reasons of security and
efficiency.
This is done for reasons of security and efficiency. Accordingly many of the java standard
library classesare final, for example: java. lang. System and java. lang. String.

All methods in a final class are implicitly final.


Ex:- public final class MyFinalClass

Final Methods: -

A final method can’t be overridden by sub-classes. This is used to prevent


unexpected behaviour from a sub class altering a method that may be crucial to the
function orconsistency of the class.
Ex: -
public class MyClass
{

public final void myFinalMethod( );


}

Final Variables: -

A final variable can only be assigned once. This assignment doesn’t grant the
variable immutable status. If the variable is a field of class, it must be assigned in the
constructor of it’sclass.

Unlike the value of a constant, the value of a final variable is not necessary know at compile
time .

Example Program:

public class Sphere


{
public static final double PI = 3.14159265d;
public final double radius;
public final double
Xpos; public final
double Ypos; public
final double Zpos;

sphere (double X, double Y, double Z, double r)


{
Radius = r;
Xpos = X;
Ypos = Y;
Zpos = Z;
}
public static void main (String args[ ])
{
Sphere obj = new Sphere(10.0, 20.0, 30.0,
5.0);System.out.println(obj.radius);
System.out.println(obj.Xpos);
System.out.println(obj.Ypos);
System.out.println(obj.Zpos);
System.out.println(PI);
}

Private method:

You can call the private method from outside the class by changing the runtime behaviour of the
class.

File: A.java

public class A {
private void message(){System.out.println("hello java"); }
}

File: MethodCall.java

import java.lang.reflect.Method;
public class MethodCall{
public static void main(String[] args)throws Exception{

Class c = Class.forName("A");
Object o= c.newInstance();
Method m =c.getDeclaredMethod("message", null);
m.setAccessible(true);
m.invoke(o, null);
}
}
Type Casting in Java:

In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically. The automatic conversion is done by the compiler and manual
conversion performed by the programmer. In this section, we will discuss type casting and its
types with proper examples.
Type casting:

Convert a value from one data type to another data type is known as type casting.

Types of Type Casting

There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

Widening Type Casting:

Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see
an example.

Ex:
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output:
Before conversion, int value 7
After conversion, long value 7
After conversion, float value 7.0

In the above example, we have taken a variable x and converted it into a long type. After that, the
long type is converted into the float type.

Narrowing Type Casting:

Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.

Ex:

public class NarrowingTypeCastingExample


{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output:
Before conversion:166.66
After conversion into long type:166
After conversion into int type:166

Abstract class in Java:

A class which is declared with the abstract keyword is known as an abstract class in Java

. It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

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.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors

and static methods also.

o It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class:

abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract
method.

Example of abstract method:

abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Interfaces:

Multiple Inheritances: -

Java doesn‟t support multiple inheritance directly. Java provides an


alternate approach known as “interfaces” to support the concept of multiple inheritance. A
java class can‟t be asub class of more than one super class, but it can implements more
than one interface.

Defining Interfaces:

An interface is basically a kind of class. Like classes, interfaces contain


methods
and variables but with a major difference. The difference is that interfaces define only abstract
methods and final fields. This means that interfaces do not specify any code to implement
these methods and datafields contain only constants. Therefore, it is responsibility of the
class that implements an interface to define the code for implementation of these methods.

The syntax for defining an interface is very similar to that for defining a class. The general
form of aninterface definition is

interface InterfaceName
{
Variable
declaration;
Methods
declaration;
}

Here, interface is the keyword and interfacename is any valid java variable(just like class names).

Variables are declared as follows:

static final type variablename=value;


Note: All variables are declared as constants. Methods declaration will contain only a list of
methodswithout any body statements.
Example: return-type methodname1(parameter_list);

Here is an example of an interface definition that contains two variables and

one method:Interface item


{
static final int code=1001;
static final String
name=”fan”;void display();
}
Note that the code for the method is not included in the interface and the method declaration
simply endswith a semicolon. The class that implements this interface must define the code
for the method.

Extending Interfaces: -

Like classes, interfaces can also be extended. That is, an interface can be sub-interfaced from
other interface. The new sub-interface will inherit all the members of the super-interface in the
manner similarto subclasses. This is achieved using the keyword “extends” as shown below:

interface name2 extends name1


{
Body of name;
}
For example: we can put all the constants in one interface and the methods in the other.
This willenable us to use the constants in classes where the methods are not required.

Example:
interface Itemconstants
{
int code =1001;
String name =
”Fan”;
}
interface Item extends Itemconstants
{
void display( );
}

We can also combine several interfaces together into a single interface. Following declarations
are valid.

interface ItemConstants
{
int code = 1001;
String name = “Fan”;
}
interface ItemMethods
{
void display ( );
}
interface Item extents ItemConstants, ItemMethods
{
------ (Body of the item)

Implementing Interfaces: -

Interfaces are used as “super-classes” whose properties are


inherited by
classes. It is therefore necessary to create a class that inherits the given interface. The general
form forextending the class and implementing an interface is as follows.

class ClassName extends SuperCalss implements interface


{
body of classname
}

Example Program: The following program illustrates to calculate the area of the rectangle and
circle.

interface Area
{
final static float PI = 3.14 f;
float compute (float x, float
y);
}
class Rectangle implements Area
{
public float compute (float x, float y)
{
return (x * y);
}
}
class Circle implements Area
{
public float compute (float x, float y)
{
return (PI * x * x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Circle cir=new Circle();
Area area; //interface object
area=rect; //area refers to rect
object
System.out.pritnln(“Area of
Rectangle=”+area.compute(10,20));area=cir; //area refers
to cir object
System.out.println(“Area of Circle=”+area.compute(10,0));
}
}

Accessing Interface Variables: -

Interfaces can be used to declare a set of constants that can be in


differentclasses. The constants values will be available to any class that implements the
interface. The values can be used in any methods, as part of any variable declaration or any
where we can use a final value.
E. g: -
interface
A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void method(int size)
{
- ---
if (size < n)
- ---
}
}

Example program for multiple inheritance using

interfaces.class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber = n;
}
void putNumber ( )
{
System.out.println(“Roll No : =”+ rollNumber);
}
}

class Test extends Student


{
float part1, part2;
void getMarks(float m1, float m2)
{
part1 =
m1;part2
= m2;
}
void putMarks( )
{
System.out.println(“Marks
Obtained”);
System.out.println(“part1 =”+
part1); System.out.println(“part2
=”+ part2);
}
}

interface Sports
{
float sportWt = 6.0 f;
void putWt( );
}

class Result extends Test implements Sports


{
float total;
public void putWt( )
{
System.out.println(“SportWt =”+ sportWt);
}
void display ( )
{
total = part1 + part2 +
sportWt;putNumber( );
putMarks
( );putWt ( );
}
}

class Hybrid
{
public static void main (String args[ ])
{
Result student1 = new
Result( );
student1.getNumber(1234);
student1.getMarks(27.0f,
33.0f);student1.display ( );
}
}

Packages: -

Packages are used to group a variety of classes and/ or interfaces. The growing is
usually
done according to functionality. Packages act as „Containers‟ for classes.

The following are benefits of packages:

1. The classes contained in the package of the other program can be easily reused.
2. In packages, classes can be unique compared with classes in other package that is,
two classes intwo different packages can have the same name.
3. Packages provide a way to hide classes.
4. Packages also provide a way for separating design form coding.

Java packages are classified into two types.

1. Java API packages 2. User-defined packages

Java API packages: -

Java API provides a large number of classes grouped into different


packages
according to functionality. Most of the time, we use the packages available with the java API.

The following figure shows the functionality break-down of packages that are frequently
used in theprogram.

JAVA

lang util apllet awt net io

Java system packages and classes:

Package Content
Name s
Language support classes. These are classes that java compiler
1. java.lang itself usesand therefore they are automatically import. They
include classes for primitive types strings, math functions,
threads and exceptions.
Language utility classes, such as vectors, hash tables, random
2. java.util
numbers, dateetc

Input and output support classes. They provide facilities for the
3. java.io
input andoutput of data.

Set of classes for implementing graphical user interface. They


4. java.awt
include classes for WINDOWS, buttons, lists, menus and etc..
Classes for networking. They include classes for communicating
5. Java.net
with local computers.

Classes for creating and implementing applets.


6.
java.applet

Using system packages:


Package „awt‟ which in-turns contain various classes for implementing graphical user interface
(GUI).There are two ways of accessing the classes stored in a package:

 The first approach is to use the fully qualified class name of the class that we want to
use. This isdone by using the package name containing the class and then appending
the class name to it using the dot (.) operator.
E. g: - java.awt.colour;
„awt‟ is a package within the package „java‟ and the hierarchy is represented by
separating thelevels with dots.

 The second approach uses the import statement to include one class or all the classes.

Syntax: import packagename.classname;


(or)

import packagename.*;
import statement must appear at the top of the file, before any class declaration.
E. g: - 1. import java.awt.colour;
2. import java.awt.*;

Naming Conventions:

The following naming conventions used for packages.


1. All package names must begin lower case letters.
2. Every package name must be unique to make the best usage of the package.
3. Duplicate names will cause run-time errors
E. g: - hyd.syntel.MyPackage;
Here „hyd‟ denotes city name and „Syntel‟ denotes organisation name.
4. A user can create a hierarchical of packages within packages by separating levels with
dots (.).

Creating packages: -

To create user-defined package, first to declare the name of the package


using the
“package” keyword followed by a package name, this must be the first statement in a java
source file(except for comment and white spaces) then we define a class, just as we
normally define a class.

Syntax: - package
packagename;
public class ClassName
{
Body of the class;
}

E. g: - package pack1;
public class A
{
Body of class A;
}
In the above example, the package name is pack1. The class „A‟ is now
considered as partof this package. The listing would be saved as a file called ”A.java” and
located in a directory named “pack1” when the source file is compiled, java will create a
“A.class file” and store it in the same directory.
The “.class” files must be located in a directory that has the same names as the
package and this directory should be a sub-directory of the directory where classes that will
import the package and class definitions. In such cases only one of the classes may be
declared as “public” and that class name with “.java” extension is the source file name. When
the source file with more than one class definition isto compile, java creates independent
“.class” files for those classes.

Accessing a (User-Defined) Package: -

The import statement can be used to access user-defined packages


same as a system packages.

The general form of import statement is:

import
package1.package2.package3.
ClassName;(Or)
import package1.*;

Here package may denote a single package (or) a hierarchy of packages. The „*‟ indicates
that the compiler should search this entire hierarchy package, when it encounters a
classname. This implies thatwe can access all classes contained in the above package
directly.

Example Program: -

Creating user-defined package.

package
pack1;public
class A
{
public void displayA( )
{
System.out.println(“Class A”);
}
}

import pack1.A;
class
PackageTest
{

public static void main (String args [ ])


{
A obj = new A
( );obj.displayA
( );
}
}

E. g2: - Inheriting package classes

import pack1;

class Inher extends A


{
void displayB( )
{
System.out.println(“class Inher”);
}
dispalyA( );
}
}

class PackageTest
{
public static void main(String args[ ])
{

Inher obj= new Inher( );


obj.displayA( );
}
}

To add a class to an existing package, the following steps are used:

1. Define the class and make it public.


2. Place the package statement.
e. g: - package pack1;
3. Store this as ClassName.java file under the directory pack1.
4. Compile this file will create a class file in the directory pack1.

E. g: - package pack1;
public class B
{
public void displayB( )
{
System.out.println(“classB”);
}
}
Now, the package pack1 will contain existing classes and
classB.import pack1.*;
Will import all the classes that are available in pack1 package.

Hiding Classes: -

When we import a package using the „*‟, all public classes are imported.
However, we
may prefer to not import certain class that is we may hide these classes from accessing
outside of thepackage. Such classes should be declared not public.

E. g: - package pack1;
public class A // public class available to outside
{
Body of A;
}

class B // not public


{
Body of B;
}

Static Import: -

Static import feature eliminates the need of qualifying a static member with the
class
name. The static import declaration, a similar to that of import. We can use the import stat to
import classes from packages and use them without qualifying the package. Similarly, we can
use the static import statement to import static members from classes and use them without
qualifying the class name.

The syntax for using the static import features is:

import static package.subpackagename.ClassNmae.staticname;


(Or)

import static package.subpackagename.ClassNmae.*;

The following program illustrates the use of static import

import static java.lang.Math.*;

public class MathOp


{
public void circle(double r)
{
double area = PI * r * r;
System.out.println(“area =”+
area);
}
public static void main (String args [ ])
{
MathOp obj= new MathOp( );
obj.circle(2.3);
}
}

You might also like