You are on page 1of 26

Class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
 fields
 methods
 constructors
 blocks
 nested class and interface
Syntax to declare a class:
class <class_name>{  
    field;  
    method;  
}  
Instance variable in Java

A variable which is created inside the class but outside the method, is known as instance variable. Instance
variable doesn't get memory at compile time. It gets memory at run time when object(instance) is created.
That is why, it is known as instance variable.

3 Ways to initialize object

There are 3 ways to initialize object in java.

1. By reference variable
2. By method
3. By constructor

Object and Class Example: main within class


In this example, we have created a Student class that have two data members id and name. We are creating
the object of the Student class by new keyword and printing the objects value.
Here, we are creating main() method inside the class through reference variables
package basics;
public class SimpleClass {

int id;//field or data member or instance variable


String name;

public static void main(String args[]){


SimpleClass s1=new SimpleClass ();//creating an object of Student
s1.id=101;
s1.name="Ram";
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
o/p
101
Ram

1
Object and Class Example-initialization through reference variables:outside main class

In real time development, we create classes and use it from another class. It is a better approach than
previous one. Let's see a simple example, where we are having main() method in another class.

We can have multiple classes in different java files or single java file. If you define multiple classes in a
single java source file, it is a good idea to save the file name with the class name which has main() method.

package basics;

class Student{
int id;
String name;
}

public class MainOutClass {


public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Ram";
System.out.println(s1.id);
System.out.println(s1.name);

}
}
o/p
101
Ram

new keyword in Java

The new keyword is used to allocate memory at run time. All objects get memory in Heap memory area.

Object and Class Example: Initialization through method


In this example, we are creating the two objects of Student class and initializing the value to these objects
by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking
the displayInformation() method.
class Student{  
 int rollno;  
 String name;  
 void insertRecord(int r, String n){  
  rollno=r;  
  name=n;  
 }  
 void displayInformation(){System.out.println(rollno+" "+name);}  
}  
class TestStudent4{  
 public static void main(String args[]){  
  Student s1=new Student();  
  Student s2=new Student();  
  s1.insertRecord(111,"Karan");  
  s2.insertRecord(222,"Aryan");  
  s1.displayInformation();  
2
  s2.displayInformation();  
 }  
}  
o/p

Output:

111 Karan
222 Aryan

Object and Class Example: Initialization through constructor

class Student{
int id;
String name;
// constructor
Student(int i, String n)
{
id=i;
name=n;

}
public void Display()
{
System.out.println("Empno "+id);
System.out.println("Ename "+name);
}
}
public class MainOutClass {
public static void main(String args[]){
Student s1=new Student(101,"Ram");
s1.Display();

}
}
o/p
Empno 101
Ename Ram

this keyword in java

Within an instance method or a constructor, this is a reference to the current object — the object whose
method or constructor is being called. You can refer to any member of the current object from within an
instance method or a constructor by using this.
Using this with a Field

3
The most common reason for using the this keyword is because a field is shadowed by a method or
constructor parameter.
For example, the Point class was written like this
public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:

public class Point {


public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
rollno=rollno;  
name=name;  
fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
class TestThis1{  
public static void main(String args[]){  
4
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword
class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  
Output:
111 ankit 5000
112 sumit 6000

Real usage of this() constructor call


The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain
between the constructors i.e. it is used for constructor chaining. Let's see the example given below that
displays the actual use of this keyword.
class Student{  
int rollno;  
String name,course;  
float fee;  
Student(int rollno,String name,String course){  
this.rollno=rollno;  
this.name=name;  
this.course=course;  
}  
Student(int rollno,String name,String course,float fee){  
this(rollno,name,course);//reusing constructor  
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  
}  
class TestThis7{  
5
public static void main(String args[]){  
Student s1=new Student(111,"ankit","java");  
Student s2=new Student(112,"sumit","java",6000f);  
s1.display();  
s2.display();  
}}  
Output:
111 ankit java null
112 sumit java 6000

Memory Management

Java Memory Management, with its built-in garbage collection, is one of the language’s finest
achievements. It allows developers to create new objects without worrying explicitly about memory
allocation and deallocation, because the garbage collector automatically reclaims memory for reuse. This
enables faster development with less boilerplate code, while eliminating memory leaks and other memory-
related problems. At least in theory.
Ironically, Java garbage collection seems to work too well, creating and removing too many objects. Most
memory-management issues are solved, but often at the cost of creating serious performance problems.
Making garbage collection adaptable to all kinds of situations has led to a complex and hard-to-optimize
system. In order to wrap your head around garbage collection, you need first to understand how memory
management works in a Java Virtual Machine (JVM).
How Garbage Collection Really Works
Many people think garbage collection collects and discards dead objects. In reality, Java garbage collection
is doing the opposite! Live objects are tracked and everything else designated garbage. As you’ll see, this
fundamental misunderstanding can lead to many performance problems.
Let’s start with the heap, which is the area of memory used for dynamic allocation. In most configurations
the operating system allocates the heap in advance to be managed by the JVM while the program is
running. This has a couple of important ramifications:
 Object creation is faster because global synchronization with the operating system is not needed for
every single object. An allocation simply claims some portion of a memory array and moves the
offset pointer forward (see Figure 2.1). The next allocation starts at this offset and claims the next
portion of the array.
 When an object is no longer used, the garbage collector reclaims the underlying memory and reuses
it for future object allocation. This means there is no explicit deletion and no memory is given back
to the operating system.

Figure 2.1: New objects are simply allocated at the end of the used heap.
All objects are allocated on the heap area managed by the JVM. Every item that the developer uses is
treated this way, including class objects, static variables, and even the code itself. As long as an object is
being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not
reachable by the application code, the garbage collector removes it and reclaims the unused memory. As
simple as this sounds, it raises a question: what is the first reference in the tree?
Garbage-Collection Roots—The Source of All Object Trees

6
Every object tree must have one or more root objects. As long as the application can reach those roots, the
whole tree is reachable. But when are those root objects considered reachable? Special objects called
garbage-collection roots (GC roots; see Figure 2.2) are always reachable and so is any object that has a
garbage-collection root at its own root.
There are four kinds of GC roots in Java:
 Local variables are kept alive by the stack of a thread. This is not a real object virtual reference and
thus is not visible. For all intents and purposes, local variables are GC roots.
 Active Java threads are always considered live objects and are therefore GC roots. This is
especially important for thread local variables.
 Static variables are referenced by their classes. This fact makes them de facto GC roots. Classes
themselves can be garbage-collected, which would remove all referenced static variables. This is of
special importance when we use application servers, OSGi containers or class loaders in general.
We will discuss the related problems in the Problem Patterns section.
 JNI References are Java objects that the native code has created as part of a JNI call. Objects thus
created are treated specially because the JVM does not know if it is being referenced by the native
code or not. Such objects represent a very special form of GC root, which we will examine in more
detail in the Problem Patterns section below.
Java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words,
it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
Advantage of Garbage Collection
 It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
How can an object be unreferenced?
There are many ways:
 By nulling the reference
 By assigning a reference to another
 By annonymous object etc.
1) By nulling a reference:
Employee e=new Employee();  
e=null;  
2) By assigning a reference to another:
Employee e1=new Employee();  
Employee e2=new Employee();  
e1=e2;//now the first object referred by e1 is available for garbage collection  
3) By annonymous object:
new Employee();  
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in Object class as:
1. protected void finalize(){}  
Note: The Garbage collector of JVM collects only those objects that are created by new keyword.
So if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
1. public static void gc(){}  

7
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.
example program
package basics;
public class GarbageCollection {
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[]){
GarbageCollection s1=new GarbageCollection();
GarbageCollection s2=new GarbageCollection();
s1=null;
s2=null;
System.gc(); //performs garbage collection
System.out.println("hello");
}
}
o/p
hello
object is garbage collected
object is garbage collected

Inheritance in Java
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.
Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name  
2. {  
3.    //methods and fields  
4. }  
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and the new class is
called child or subclass

Java Inheritance Example

8
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship
between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.

class Employee{  
 float salary=40000;  
}  
class Programmer extends Employee{  
 int bonus=10000;  
 public static void main(String args[]){  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class
i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.

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

9
Single Inheritance Example
File: TestInheritance.java
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class TestInheritance{  
public static void main(String args[]){  
Dog d=new Dog();  
d.bark();  
d.eat();  
}}  
Output:
barking...
eating...

Multilevel Inheritance Example


File: TestInheritance2.java
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class BabyDog extends Dog{  
void weep(){System.out.println("weeping...");}  
}  
class TestInheritance2{  
public static void main(String args[]){  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}}  
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
class Animal{  
10
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class Cat extends Animal{  
void meow(){System.out.println("meowing...");}  
}  
class TestInheritance3{  
public static void main(String args[]){  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
}}  
Output:
meowing...
eating...

Super keyword
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.
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();  
}
}  
Output:
black
white

Another Example from Text book

This second form of super is most applicable to situations in which member names of
a subclass hide members by the same name in the superclass. Consider this simple class
hierarchy:

// Using super to overcome name hiding.


class A {
11
int i;
}

// Create a subclass by extending class A.


class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}

This program displays the following:


i in superclass: 1
i in subclass: 2

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.

class Animal{  
void eat()
{
System.out.println("eating...");}  
}  
class Dog extends Animal{  
void eat()
{
System.out.println("eating bread...");
}  
void bark()
{
System.out.println("barking...");
}  
void work()
{  
super.eat();  
bark();  
}  
}  
class TestSuper2{  
public static void main(String args[]){  
Dog d=new Dog();  
d.work();  
12
}
}  

Output:
eating...
barking...

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
class Animal{  
Animal()
{
System.out.println("animal is created");
}  
}  

class Dog extends Animal
{  
Dog()
{  
super();  
System.out.println("dog is created");  
}  
}  

class TestSuper3{  
public static void main(String args[])
{  
Dog d=new Dog();  
}
}
o/p

animal is created
dog is created

super example: real use


Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person
will be inherited to Emp by default. To initialize all the property, we are using parent class constructor
from child class. In such way, we are reusing the parent class constructor.
class Person{  
int id;  
String name;  
Person(int id,String name)
{  
this.id=id;  
this.name=name;  
}  
}  
class Emp extends Person{  
float salary;  
Emp(int id,String name,float salary)
{  
super(id,name);//reusing parent constructor  
13
this.salary=salary;  
}  
void display()
{
System.out.println(id+" "+name+" "+salary);
}  
}  

class TestSuper5{  
public static void main(String[] args){  
Emp e1=new Emp(1,"ankit",45000f);  
e1.display();  
}
}  
Output:
1 ankit 45000
  
since super( ) must be the first statement executed in a subclass’ constructor, this order is the same whether
or not super( ) is used. If super( ) is not used, then the default or parameterless constructor of each super
class will be executed. The following program illustrates when constructors are executed:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor

Method overloading in java

package basics;

class Overload {
14
double volume(float l, float w, float h) {
return l * w * h;
}

double volume(float l) {
return l * l * l;
}

double volume(float r, float h) {


return 3.1416 * r * r * h;
}
}
public class VolumeUsingMethodoverloading {
public static void main(String args[]) {
Overload overload = new Overload();
double rectangleBox = overload.volume(5, 8, 9);
System.out.println("Volume of ractangular box is " + rectangleBox);
System.out.println("");
double cube = overload.volume(5);
System.out.println("Volume of cube is " + cube);
System.out.println("");
double cylinder = overload.volume(6, 12);
System.out.println("Volume of cylinder is " + cylinder);
}
}

o/p

Volume of ractangular box is 360.0


Volume of cube is 125.0
Volume of cylinder is 1357.1712

Method Overriding

In a class hierarchy, when a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of the method defined
by the superclass will be hidden. Consider the following:

// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}

// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
15
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the version of show( ) inside B overrides the version declared in A.
If you wish to access the superclass version of an overridden method, you can do so by
using super. For example, in this version of B, the superclass version of show( ) is invoked
within the subclass’ version.
This allows all instance variables to be displayed.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
output:
i and j: 1 2
k: 3

Here, super.show( ) calls the superclass version of show( ).


Method overriding occurs only when the names and the type signatures of the two
methods are identical. If they are not, then the two methods are simply overloaded. For
example, consider this modified version of the preceding example:

// Methods with differing type signatures are overloaded – not


// overridden.

class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
16
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}

// Create a subclass by extending class A.


class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}

The output produced by this program is shown here:


This is k: 3
i and j: 1 2

The version of show( ) in B takes a string parameter. This makes its type signature
different from the one in A, which takes no parameters. Therefore, no overriding (or name
hiding) takes place. Instead, the version of show( ) in B simply overloads the version of
show( ) in A.

Exception handling in Java


An Exception can be anything which interrupts the normal flow of the program. When an exception occurs program
processing gets terminated and doesn’t continue further. In such cases we get a system generated error message. The
good thing about exceptions is that they can be handled. We will cover the handling part later in this same tutorial.

When an exception can occur?


Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time
exceptions).

Reasons for Exceptions


There can be several reasons for an exception. For example, following situations can cause an exception – Opening a
non-existing file, Network connection problem, Operands being manipulated are out of prescribed ranges, class file
missing which was supposed to be loaded and so on.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error
defines problems that are not expected to be caught under normal circumstances by our program. For example
17
memory error, hardware error, JVM error etc.
Exceptions are the conditions within code which a developer can handle and take necessary corrective actions. Few
examples –

 DivideByZero exception
 NullPointerException
 ArithmeticException
 ArrayIndexOutOfBoundsException

Advantages of Exception Handling


 Exception handling allows us to control the normal flow of the program by using exception handling in
program.
 It throws an exception whenever a calling method encounters an error providing that the calling method
takes care of that error.
 It also gives us the scope of organizing and differentiating between different error types using a separate
block of codes. This is done with the help of try-catch blocks.
Why to handle exception?
If an exception is raised, which has not been handled by programmer then program execution can get terminated and
system prints a non user friendly error message.
Ex:-Take a look at the below system generated exception
An exception generated by the system is given below
Exception in thread "main" java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
For a novice user the above message won’t be easy to understand. In order to let them know that what went wrong
we use exception handling in java program. We handle such conditions and then prints a user friendly warning
message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by
user.

Types of exceptions
There are two types of exceptions
1)Checked exceptions
2)Unchecked exceptions

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during
compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in
the program, it will give compilation error.

Examples of Checked Exceptions :-


ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer
has handled them or not but it’s the duty of the programmer to handle these exceptions and provide a safe exit.
These exceptions need not be included in any method’s throws list because compiler does not check to see if a
method handles or throws these exceptions.

Examples of Unchecked Exceptions:-


ArithmeticException
ArrayIndexOutOfBoundsException

18
NullPointerException
NegativeArraySizeException etc.

Exception hierarchy

Example program for exception handling


import java.util.Scanner;

public class DivideByZero {


public static void main(String[] args) {
int a, b, result;

Scanner input = new Scanner(System.in);


System.out.println("Input two integers");

a = input.nextInt();
b = input.nextInt();
// try block
try {
result = a / b;
System.out.println("Result = " + result);
}

// catch block

catch (ArithmeticException e) {
System.out.println("Divide by zero Exception caught: Don't divide by zero. "+e);
}
}
}

19
o/p
Input two integers
3
0
Divide by zero Exception caught: Don't divide by zero. java.lang.ArithmeticException: / by zero

Java Package

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.
 User-defined-package:- Java package created by user to categorized classes and interface

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

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();
}
}
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.
NOTE : Development directory is the directory where your JDK is install.

Uses of java package

20
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;
class MyDate extends Date
{
//statement.
}
3. import all the classes from the particular package
Example :
import java.util.*;
class MyDate extends Date
{
//statement;
}

import statement is kept after the package statement.


Example :
package mypack;
import java.util.*;
But if you are not creating any package then import statement will be the first statement of your java source file.

Static import
static import is a feature that expands the capabilities of import keyword. It is used to import static member of a class. We all
know that static member are referred in association with its class name outside the class. Using static import, it is possible to
refer to the static member directly without its class name. There are two general form of static import statement.
 The first form of static import statement, import only a single static member of a class
Syntax
import static package.class-name.static-member-name;
Example
import static java.lang.Math.sqrt; //importing static method sqrt of Math class
 The second form of static import statement,imports all the static member of a class
Syntax
import static package.class-type-name.*;
Example
import static java.lang.Math.*; //importing all static member of Math class

Example without using static import


public class Test
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(144));
}
}
Output :
12

Example using static import


import static java.lang.Math.*;
public class Test
{
21
public static void main(String[] args)
{
System.out.println(sqrt(144));
}
}
Output :
12

Example : Without Static Imports


class Demo1{
public static void main(String args[])
{
double var1= Math.sqrt(5.0);
double var2= Math.tan(30);
System.out.println("Square of 5 is:"+ var1);
System.out.println("Tan of 30 is:"+ var2);
}
}
Output: what’s the use of static imports?
Static imports are used to save your time and typing. If you hate to type same thing again and again then you may find such
imports interesting.
Lets understand
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276
Example 2: Using Static Imports
import static java.lang.System.out;
import static java.lang.Math.*;
class Demo2{
public static void main(String args[])
{
//instead of Math.sqrt need to use only sqrt
double var1= sqrt(5.0);
//instead of Math.tan need to use only tan
double var2= tan(30);
//need not to use System in both the below statements
out.println("Square of 5 is:"+var1);
out.println("Tan of 30 is:"+var2);
}
}
Output:
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276
Points to note:
1) Package import syntax:
import static java.lang.System.out;
import static java.lang.Math.*;

Java Access Protection

Class Member Access


When a member doesn't have an explicit access specification, then it is visible to the Classes and packages are means of
encapsulating and containing the name space and scope of the variables and methods.
Packages behaves as containers for classes and other subordinate packages.
Classes act as containers for data and code.
Class Members Visibility
The Java's smallest unit of abstraction is class. Because of the interplay between the classes and packages, Java addresses the
following four categories of visibility for class members :
 Subclasses in same package
 Non-subclasses in same package
 Subclasses in different packages
 Classes that are neither in same package nor in subclasses
The three access modifiers are :
 public

22
 private
 protected
provides a variety of ways to produce many levels of access required by these categories. The upcoming table sums up the
interaction
While the access control mechanism of Java may seem complicated, we can simplify it as follows.
Anything declared as public can be accessed from anywhere.
Anything declared as private can't be seen outside of its class.
subclasses as well as to the other classes in the same package. This is the default access. And If you want to allow an element to
be seen outside your current package, but only to the classes that subclass your class directly, then declare that element
protected.
Private Protected Public No Modifier
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No Yes Yes No
Different package non-subclass No No Yes No

This table applies only to the members of classes. A non-nested class has only two possible access levels i.e., default and
public.
When a class is declared as public, then it is accessible by any other code. If a class has default access, then it can only be
accessed by the other code within its same package. When a class is public, it must be only the public class declared in the file
that must have the same name as the class.
Java Access Protection Example
Here the upcoming example allows all the combinations of access control modifiers. This example has two packages and five
classes.
Always remember that the classes for the two different packages need to be stored in directories after their respective packages
(in this case pkg1 and pkg2).
The source for the first package defines the three classes i.e., Protection, Derived, and SamePackage. The first class defines the
four variables of type int in each of the legal protection modes. The variable n declared with the default protection, the variables
n_priv, n_prot, and n_publ is private, protected, and public respectively.
Each subsequent class in the following example will try to access the variables in an instance of this class. The lines that will not
compile due to the access restrictions are commented out. Before each of these lines is a comment that listing the places from
which this level of protection would allow access.
The second class named Derived, is a subclass of Protection in the same package, pkg1. This grants Derived access to every
variable in the class Protection except for n_priv, the private one. The third class named SamePackage, is not a subclass of the
class Protection, but is in the same package and also has access to all but not n_priv.
This is Protection.java file:
package pkg1;

public class Protection


{
int n = 1;
private int n_priv = 2;
protected int n_prot = 3;
public int n_publ = 4;

public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv);
System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}
This is Derived.java file:
package pkg1;

class Derived extends Protection


{
Derived()
{
System.out.println("derived constructor");
23
System.out.println("n = " + n);

/* class only
* System.out.println("n_priv = "4 + n_priv); */

System.out.println("n_prot = " + n_prot);


System.out.println("n_publ = " +n_publ);
}
}
This is SamePackage.java file:
package pkg1;

class SamePackage
{
SamePackage()
{
Protection pro = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + pro.n);

/* class only
* System.out.println("n_priv = " + pro.n_priv); */

System.out.println("n_prot = " + pro.n_prot);


System.out.println("n_publ = " + pro.n_publ);
}
}
Following is the source code for the other package named pkg2. The two classes defined in the package pkg2 cover the outer
two conditions that are affected by the access control. The first class named Protection2, is a subclass of pkg1.Protection. This
grants access to all of pkg1. Variables of the class Protection except for n_priv (because it is private) and n, the variable
declared with the default protection.
Always remember that the default only allows access from within the class or the package, not extra-package subclasses.
Finally, the class OtherPackage has access to n_publ only which was declared as public.
This is Protection2.java file:
package pkg2;

class Protection2 extends pkg1.Protection


{
Protection2()
{
System.out.println("derived other package constructor");

/* class or package only


* System.out.println("n = " + n); */

/* class only
* System.out.println("n_priv = " + n_priv); */

System.out.println("n_prot = " + n_prot);


System.out.println("n_publ = " + n_publ);
}
}
This is OtherPackage.java file:
package pkg2;

class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();

System.out.println("other package constructor");

24
/* class or package only
* System.out.println("n = " + pro.n); */

/* class only
* System.out.println("n_priv = " + pro.n_priv); */

/* class, subclass or package only


* System.out.println("n_prot = " + pro.n_prot); */

System.out.println("n_publ = " + pro.n_publ);


}
}
If you want to try these two packages, here are two test files you can use.
The one for package pkg1 is shown here:
/* demo package pkg1 */

package pkg1;

/* instantiate the various classes in pkg1 */


public class Demo
{
public static void main(String args[])
{
Protection obj1 = new Protection();
Derived obj2 = new Derived();
SamePackage obj3 = new SamePackage();
}
}
The test file for pkg2 is shown below :
/* demo package pkg2 */

package pkg2;

/* instantiate the various classes in pkg2 */


public class Demo
{
public static void main(String args[])
{
Protection2 obj1 = new Protection2();
OtherPackage obj2 = new OtherPackage();
}
}

Interface
Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods
declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are
public, static & final by default.

What is the use of interfaces?


As mentioned above they are used for abstraction. Since methods in interfaces do not have body, they have to be implemented
by the class before you can access them. The class that implements interface must implement all the methods of that interface.
Also, java programming language does not support multiple inheritance, using interfaces we can achieve this as a class can
implement more than one interfaces, however it cannot extend more than one classes
Declaration
Interfaces are declared by specifying a keyword “interface”. E.g.:
interface MyInterface
{
/* All the methods are public abstract by default
* Note down that these methods are not having body
*/
public void method1();
public void method2();
}
25
Benefits of having interfaces:
Following are the advantages of using interfaces:
1. Without bothering about the implementation part, we can achieve the security of implementation
2. In java, multiple inheritance is not allowed, However by using interfaces you can achieve the same . A class can
extend only one class but can implement any number of interfaces. It saves you from Deadly Diamond of Death(DDD)
problem.
Example program

//Area Of Rectangle and Triangle using Interface

interface Area
{
float compute(float x, float y);
}

class Rectang implements Area


{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triang implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class Multinheritance
{
public static void main(String args[])
{
Rectang rect = new Rectang();
Triang tri = new Triang();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(1,2));

area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
}
}
/* * OUTPUT **

Area Of Rectangle = 2.0


Area Of Triangle = 10.0
*/

26

You might also like