Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Unit 3 Notes

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

JAVA, BCA 2nd SEM

UNIT – 3

Inheritance
Inheritance in Java: inheritance is an important pillar of OOP. It is the mechanism in Java by
which one class is allow to inherit the features( fields and methods) of another class.

Important terminologies
Super class: the class whose features are in a rated is known as super class or a base class are a
parent class.

Subclass: the class that inherits the other class is known as subclass or a derived class, extended
class or child class. The subclasses can add its own fields and methods in addition to the
superclass fields and methods.

Re usability: inheritance supports the concept of reusability. that is, when we want to create a
new class and there is already a class that include some of the code that we want, we can derive
our own class from the existing class by doing this, we are reusing the fields and methods of the
existing class.

How to use inheritance in Java:


The keyword used for inheritance is extends

syntax
class derived- class extends- base class
{
// methods and fields
}

Example for inheretence.


class Room
{
int length;
int breath;
Room( int,x int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth)
}
}
class Bedroom extends Room
{

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

int height;
Bedroom(int x,int y,int z)
{
super(x,y);
height=z;
}
int volume()
{
return(lengh * breadth);
}
}
}
class Inhertest
{
public static void main(string args[])
{
int area1=room1.area();
int volume1=room1.volume;
System.out,println(“Area1=”+area);
System.out.println(“Volume1=”+volume);
}
}

Types of inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance

1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In
the image below, class A serves as a base class for the derived class B.

// Java program to illustrate the concept of single inheritance


import java.io.*;
import java.lang.*;
import java.util.*;

class one {
public void print_geek()

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main {
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base


class and as well as the derived class also act as the base class to other class. In the below image,
class A serves as a base class for the derived class B, which in turn serves as a base class for the
derived class C. In Java, a class cannot directly access the grandparent’s members.

// Java program to illustrate the concept of Multilevel inheritance


import java.io.*;
import java.lang.*;
import java.util.*;

class one

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for() { System.out.println("for"); }
}

class three extends two


{
public void print_geek()
{
System.out.println("Geeks");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base


class) for more than one subclass. In the below image, class A serves as a base class for the
derived class B, C and D.

// Java program to illustrate the concept of Hierarchical inheritance

class A
{
public void print_A() { System.out.println("Class A"); }
}

class B extends A
{
public void print_B() { System.out.println("Class B"); }
}

class C extends A
{
public void print_C() { System.out.println("Class C"); }
}

class D extends A
{
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have
more than one superclass and inherit features from all parent classes. Please note that Java does
not support multiple inheritances with classes. In java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interface A and B.

// Java program to illustrate the concept of Multiple inheritance


import java.io.*;
import java.lang.*;
import java.util.*;

interface one
{
public void print_geek();
}

interface two
{
public void print_for();
}

interface three extends one, two


{

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

public void print_geek();


}
class child implements three
{
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}

// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of


inheritance. Since java doesn’t support multiple inheritances with classes, hybrid inheritance
is also not possible with classes. In java, we can achieve hybrid inheritance only
through Interfaces.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Why multiple inheritance is not supported in Java


In Java, a class cannot extend more than one class. Therefore following is illegal .
However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritances.
The reason behind this is to prevent ambiguity.
Consider a case where class B extends class A and Class C and both class A and C have the
same method msg().
Now java compiler cannot decide, which display method it should inherit. To prevent such
situation, multiple inheritances is not allowed in java.

Example
class A
{
void msg()
{
System.out.println(“Hello”);
}
class B
{
void msg()
{
System.out.println(“Welcome”);
}
class C extends A,B //multiple inheretence
{
Public Static void main(String args[])
{
C.obj=new C();
obj.msg();// now which method msg() would be invoked?
}
}

Output: compile time error.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Polymorphism in Java is a concept by which we can perform a single action in 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.

1.Compile time polymorphism:

Compile time polymorphism is a polymorphism that is resolved during compilation


process

We can perform Compile time polymorphism in java by method overloading and


Operator overloading.

Method overloading:

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.

Example:
void gfgcw() {........}
void gfgcw(int num1) {........}
void gfgcw(float num1) {........}
void gfgcw(int num1,float num2) {........}

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

1.By changing number of arguments


2.By changing the data type

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

1. Method Overloading by By changing number of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

class Adder

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

class TestOverloading1

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

2) Method Overloading by changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{

static int add(int a, int b){return a+b;}

static double add(double a, double b){return a+b;}

class TestOverloading2{

public static void main(String[] args){

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

Operator overloading:

An operator is said to be overloaded if it can be used to perform more than one function.
Operator overloading is overloading method in which an existing operator is given a new
meaning in Java + operator is overloaded. Java, on the other hand, does not allow for user-
defined operator overloading. To add integer, + can be employed as an arithmetic addition
operator. It can also be used to join string together.

example

public class GFGCW

void add(int a,int b)

int sum=a+b;

System.out.println(“Addition of two integer:”+sum);

void add(String s1, String s2)

Stringcon_str=s1+s2;

System.out,plrintln(“concatation of two strings :”+con_str);

public static void main(String args[])

GFGCW obj=new GFGCW();

obj.add(10,10);

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

obj.add(“Operator”,”overloading”);

Advantages of compile time polymorphism

1. Get improves call clarity and allows for the use of a single name for several
procedures
2. it as a faster execution time since i....ered early in the compilation process.it as a faster
execution time since it is discovered early in the compilation process

Run time polymorphism:

Runtime polymorphism in Java is also popularly known as Dynamic Binding or Dynamic


Method Dispatch. In this process, the call to an overridden method is resolved dynamically at
runtime rather than at compile-time. You can achieve Runtime polymorphism via Method
Overriding.

Upcasting : Overriding is done by using a reference variable of the superclass. The method to
be called is determined based on the object which is being referred to by the reference
variable. This is also known as Upcasting.

Upcasting takes place when the Parent class’s reference variable refers to the object of the
child class. For example:

class A{}

class B extends A{}

A a=new B(); //upcasting

Examples of Runtime Polymorphism in Java

class Bike

void run()

System.out.println(“running”);

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

class Splendor extends Bike

void run()

System.out.println(“running safely with 60km”);

public ststic void main(String args[])

Bike b=new Splendor();//Upcasting

b.run();

Difference between compile time and run time polymorphism

Sr. Key Compile-time Runtime polymorphism


No. polymorphism

1 Basic Compile time R un time polymorphism where


polymorphism means at run time we came to know
binding is occuring at which method is going to
compile time invoke

2 Static/Dynamic It can be achieved through


Binding dynamic binding
It can be achieved through
static binding

4. Inheritance Inheritance is not involved Inheritance is involved

5 Example Method overloading is an Method overriding is an


example of compile time example of runtime
polymorphism polymorphism

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Dynamic binding:

What is binding?
Connecting a method call to the method body is known as binding.

There are two types of binding


Static Binding (also known as Early Binding).
Dynamic Binding (also known as Late Binding).

Understanding Type
Let's understand the type of instance.
1) variables have a type
data variable is a type of int.

2) References have a type


class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}

3) Objects have a type


An object is an instance of particular java class,but it is also an instance of its superclass.
class Animal{}

class Dog extends Animal{


public static void main(String args[]){
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.

Static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.

If there is any private, final or static method in a class, there is static binding.
Example of static binding
class Dog
{
private void eat()
{

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

System.out.println("dog is eating...");
}

public static void main(String args[])


{
Dog d1=new Dog();
d1.eat();
}
}

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal
{
void eat()
{
System.out.println("animal is eating...");
}
}

class Dog extends Animal


{
void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Animal a=new Dog();
a.eat();
}
}

Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes
the code stable by detecting the bugs at compile time.

Before generics, we can store any type of objects in the collection, i.e., non-generic. Now
generics force the java programmer to store a specific type of objects.

Advantage of Java Generics


There are mainly 3 advantages of generics. They are as follows:

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

1.Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
Without Generics, we can store any type of objects.

List list = new ArrayList();


list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error

2) Type casting is not required: There is no need to typecast the object.


Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error

Syntax to use generic collection


ClassOrInterface<Type>

Example to use Generics in java


ArrayList<String>

Example of Generics in Java


Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

list.add("rahul");
list.add("jai");
//list.add(32);//compile time error

String s=list.get(1);//type casting is not required


System.out.println("element is: "+s);

Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error

String s=list.get(1);//type casting is not required


System.out.println("element is: "+s);

Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Types of Java Generics


1.Generic Class:
A class that can refer to any type is known as a generic class. Here, we are using the T type
parameter to create the generic class of specific type.

Let's see a simple example to create and use the generic class.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Creating a generic class:


class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
The T type indicates that it can refer to any type (like String, Integer, and Employee). The type
you specify for the class will be used to store and retrieve the data.

Let's see the code to use the generic class.

class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());
}}

Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
common type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value

Generic Method
Like the generic class, we can create a generic method that can accept any type of arguments.
Here, the scope of arguments is limited to the method where it is declared. It allows static as well
as non-static methods.

Let's see a simple example of java generic method to print array elements. We are using here E
to denote the element.

public class TestGenerics4{

public static < E > void printArray(E[] elements) {


for ( E element : elements){
System.out.println(element );
}
System.out.println();
}

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

public static void main( String args[] ) {


Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };

System.out.println( "Printing Integer Array" );


printArray( intArray );

System.out.println( "Printing Character Array" );


printArray( charArray );
}
}

Instance of operator
The instanceof operator in Java is used to check whether an object is an instance of a particular
class or not.

Its syntax is
objectName instanceOf className;
Here, if objectName is an instance of className, the operator returns true. Otherwise, it returns
false.

class Main
{
public static void main(String[] args)
{
// create a variable of string type
String name = "Programiz";

// checks if name is instance of String


boolean result1 = name instanceof String;
System.out.println("name is an instance of String: " + result1);

// create an object of Main


Main obj = new Main();

// checks if obj is an instance of Main


boolean result2 = obj instanceof Main;
System.out.println("obj is an instance of Main: " + result2);
}
}

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).

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

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.

Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors
and static methods also.
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();
}
}

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Difference between abstract class and abstract methods

Abstract classes Abstract methods

Abstract classes can’t be instantiated. Abstract method bodies must be empty.

Sub-classes must implement the abstract class’s


Other classes extend abstract classes. abstract methods.

Can have both abstract and concrete


methods. Has no definition in the class.

Interface
An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Interface Example
In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Multiple inheritance in java


interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Multiple inheritance is not supported through class in java, but it is possible by an


interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case
of class because of ambiguity. However, it is supported in case of an interface because there is
no ambiguity. It is because its implementation is provided by the implementation class.

For example:
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Super Keyword

The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

Example

class Animal{

String color="white";

class Dog extends Animal{

String color="black";

void printColor(){

System.out.println(color);//prints color of Dog class

System.out.println(super.color);//prints color of Animal class

class TestSuper1{

public static void main(String args[]){

Dog d=new Dog();

d.printColor();

}}

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Packages in java
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Example
/save as Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file.

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.

How to access package from another package?

There are three ways to access the package from outside the package.

import package.*;

import package.classname;

fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.

Example of package that import the packagename.*

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name

//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

obj.msg();

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Output:Hello

If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.

Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular
group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket
classes are for networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related classes in io package,
Server and ServerSocket classes in net packages and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean or


org.sssit.dao.

Example of Subpackage

package com.javatpoint.core;

class Simple{

public static void main(String args[]){

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

To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

Java.util Package

It contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).

Following are the Important Classes in Java.util package :

AbstractCollection: This class provides a skeletal implementation of the Collection interface, to


minimize the effort required to implement this interface.

AbstractList: This class provides a skeletal implementation of the List interface to minimize the
effort required to implement this interface backed by a “random access” data store (such as an
array).

AbstractMap<K,V>: This class provides a skeletal implementation of the Map interface, to


minimize the effort required to implement this interface.

AbstractMap.SimpleEntry<K,V>: An Entry maintaining a key and a value.

AbstractMap.SimpleImmutableEntry<K,V>: An Entry maintaining an immutable key and value.

AbstractQueue: This class provides skeletal implementations of some Queue operations.

AbstractSequentialList: This class provides a skeletal implementation of the List interface to


minimize the effort required to implement this interface backed by a “sequential access” data
store (such as a linked list).

AbstractSet: This class provides a skeletal implementation of the Set interface to minimize the
effort required to implement this interface.

ArrayDeque: Resizable-array implementation of the Deque interface.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

ArrayList: Resizable-array implementation of the List interface.

Arrays: This class contains various methods for manipulating arrays (such as sorting and
searching).

BitSet: This class implements a vector of bits that grows as needed.

Calendar: The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting
the date of the next week.

Collections: This class consists exclusively of static methods that operate on or return
collections.

Currency: Represents a currency.

Date: The class Date represents a specific instant in time, with millisecond precision.

Dictionary<K,V>: The Dictionary class is the abstract parent of any class, such as Hashtable,
which maps keys to values.

EnumMap,V>: A specialized Map implementation for use with enum type keys.

EnumSet: A specialized Set implementation for use with enum types.

EventListenerProxy: An abstract wrapper class for an EventListener class which associates a set
of additional parameters with the listener.

EventObject: The root class from which all event state objects shall be derived.

FormattableFlags: FomattableFlags are passed to the Formattable.formatTo() method and


modify the output format for Formattables.

Formatter: An interpreter for printf-style format strings.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.


JAVA, BCA 2nd SEM

GregorianCalendar: GregorianCalendar is a concrete subclass of Calendar and provides the


standard calendar system used by most of the world.

HashMap<K,V>: Hash table based implementation of the Map interface.

HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap
instance).

Hashtable<K,V>: This class implements a hash table, which maps keys to values.

IdentityHashMap<K,V>: This class implements the Map interface with a hash table, using
reference-equality in place of object-equality when comparing keys (and values).

LinkedHashMap<K,V>: Hash table and linked list implementation of the Map interface, with
predictable iteration order.

LinkedHashSet: Hash table and linked list implementation of the Set interface, with predictable
iteration order.

LinkedList: Doubly-linked list implementation of the List and Deque interfaces.

NAVEEN V S,DEPT OF BCA, GFGCW,TUMKUR.

You might also like