0% found this document useful (0 votes)
7 views50 pages

Java 4

Polymorphism in Java allows a single action to be performed in multiple ways, categorized into compile-time and runtime polymorphism. Runtime polymorphism is achieved through method overriding, where the method invoked is determined at runtime based on the object type. The document also discusses concepts like upcasting, downcasting, the instanceof operator, and abstract classes, illustrating these with various code examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views50 pages

Java 4

Polymorphism in Java allows a single action to be performed in multiple ways, categorized into compile-time and runtime polymorphism. Runtime polymorphism is achieved through method overriding, where the method invoked is determined at runtime based on the object type. The document also discusses concepts like upcasting, downcasting, the instanceof operator, and abstract classes, illustrating these with various code examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Polymorphism in Java

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

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

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

Runtime Polymorphism in Java

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


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

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

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

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

class A{}
class B extends A{}
A a=new B();//upcasting

1
Example of Java Runtime Polymorphism

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

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

1. class Bike{
2. void run(){[Link]("running");}
3. }
4. class Splender extends Bike{
5. void run(){[Link]("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. [Link]();
10. }
11. }
Test it Now
Output: running safely with 60km.

Real example of Java Runtime Polymorphism

Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of
interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide
8%, 7% and 9% rate of interest.

2
Note: It is also given in method overriding but there was no upcasting.

1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test3{
17. public static void main(String args[]){
18. Bank b1=new SBI();
19. Bank b2=new ICICI();
20. Bank b3=new AXIS();
21. [Link]("SBI Rate of Interest: "+[Link]());
22. [Link]("ICICI Rate of Interest: "+[Link]());
23. [Link]("AXIS Rate of Interest: "+[Link]());
24. }
25. }

Output:

3
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Java Runtime Polymorphism with data member

Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data
members.

In the example given below, both the classes have a datamember speedlimit, we are accessing
the datamember by the reference variable of Parent class which refers to the subclass object.
Since we are accessing the datamember which is not overridden, hence it will access the
datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.


1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda3();
9. [Link]([Link]);//90
10. }

Output: 90

Java Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

1. class Animal{
2. void eat(){[Link]("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){[Link]("eating fruits");}

4
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){[Link]("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. [Link]();
19. [Link]();
20. [Link]();
21. }
22. }

Output: eating
eating fruits
drinking Milk

Try for Output

1. class Animal{
2. void eat(){[Link]("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){[Link]("dog is eating...");}
7. }
8.
9. class BabyDog1 extends Dog{
10. public static void main(String args[]){
11. Animal a=new BabyDog1();
12. [Link]();
13. }}

Output: Dog is eating

Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.

5
Static Binding and Dynamic Binding

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

There are two types of binding

1. Static binding (also known as early binding).


2. Dynamic binding (also known as late binding).

Understanding Type

Let's understand the type of instance.

1) Variables have a type

Each variable has a type; it may be primitive and non-primitive.

1. int data=30;

Here data variable is a type of int.

2) References have a type

1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }

3) Objects have a type


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

1. class Animal{}
2.
3. class Dog extends Animal{
6
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }

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

1. class Dog{
2. private void eat(){[Link]("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. [Link]();
7. }
8. }

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

1. class Animal{
2. void eat(){[Link]("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){[Link]("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. [Link]();
11. }

7
12. }

Output:dog is eating...

In the above example object type cannot be determined by the compiler, because the instance of
Dog is also an instance of [Link] compiler doesn't know its type, only its base type.

8
Java instanceof
 java instanceof
 Example of instanceof operator
 Applying the instanceof operator with a variable the have null value
 Downcasting with instanceof operator
 Downcasting without instanceof operator

The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.

Simple example of java instanceof

Let's see the simple example of instance operator where it tests the current class.

1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. [Link](s instanceof Simple);//true
5. }
6. }

Output: true

An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be referred by either Dog or Animal class.

Another example of java instanceof operator

1. class Animal{}
2. class Dog1 extends Animal{//Dog inherits Animal
3.
4. public static void main(String args[]){
5. Dog1 d=new Dog1();
6. [Link](d instanceof Animal);//true
7. }
8. }
Output: true

9
instanceof in java with a variable that have null value

If we apply instanceof operator with a variable that have null value, it returns false. Let's see the
example given below where we apply instanceof operator with the variable that have null value.

1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. [Link](d instanceof Dog2);//false
5. }
6. }

Output: false

Downcasting with java instanceof operator

When Subclass type refers to the object of Parent class, it is known as downcasting. If we
perform it directly, compiler gives Compilation error. If you perform it by typecasting,
ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is
possible.

1. Dog d=new Animal();//Compilation error

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

1. Dog d=(Dog)new Animal();


2. //Compiles successfully but ClassCastException is thrown at runtime

Possibility of downcasting with instanceof

Let's see the example, where downcasting is possible by instanceof operator.

1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting

10
7. [Link]("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog3();
13. [Link](a);
14. }
15.
16. }

Output: ok downcasting performed

Downcasting without the use of java instanceof

Downcasting can also be performed without the use of instanceof operator as displayed in the
following example:

1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. [Link]("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. [Link](a);
10. }
11. }

Output: ok downcasting performed

Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we
downcast it, it is fine. But what will happen if we write:

1. Animal a=new Animal();


2. [Link](a);
3. //Now ClassCastException but not in case of instanceof operator

11
Understanding Real use of instanceof in java

Let's see the real use of instanceof keyword by the example given below.

1. interface Printable{}
2. class A implements Printable{
3. public void a(){[Link]("a method");}
4. }
5. class B implements Printable{
6. public void b(){[Link]("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
19.
20. }
21. }//end of Call class
22.
23. class Test4{
24. public static void main(String args[]){
25. Printable p=new B();
26. Call c=new Call();
27. [Link](p);
28. }
29. }

Output: b method

12
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).

Before learning 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 important things to the user and hides the internal details for
example sending sms, you just 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 Abstaction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.

Example abstract class

1. abstract class A{}

Abstract method

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

13
Example abstract method

1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

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

1. abstract class Bike{


2. abstract void run();
3. }
4.
5. class Honda4 extends Bike{
6. void run(){[Link]("running safely..");}
7.
8. public static void main(String args[]){
9. Bike obj = new Honda4();
10. [Link]();
11. }
12. }

running safely..

Understanding the real scenario of abstract class

In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end
user) and object of the implementation class is provided by the factory method.

A factory method is the method that returns the instance of the class. We will learn about the
factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.

File: [Link]

1. abstract class Shape{


2. abstract void draw();
3. }

14
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){[Link]("drawing rectangle");}
7. }
8.
9. class Circle1 extends Shape{
10. void draw(){[Link]("drawing circle");}
11. }
12.
13. //In real scenario, method is called by programmer or user
14. class TestAbstraction1{
15. public static void main(String args[]){
16. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() met
hod
17. [Link]();
18. }
19. }

drawing circle

Another example of abstract class in java

File: [Link]

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 7;}
7. }
8. class PNB extends Bank{
9. int getRateOfInterest(){return 7;}
10. }
11.
12. class TestBank{
13. public static void main(String args[]){
14. Bank b=new SBI();//if object is PNB, method of PNB will be invoked
15. int interest=[Link]();
16. [Link]("Rate of Interest is: "+interest+" %");
17. }}
Rate of Interest is: 7 %

15
Abstract class having constructor, data member, methods etc.

An abstract class can have data member, abstract method, method body, constructor and even
main() method.

File: [Link]

1. //example of abstract class that have method body


2. abstract class Bike{
3. Bike(){[Link]("bike is created");}
4. abstract void run();
5. void changeGear(){[Link]("gear changed");}
6. }
7.
8. class Honda extends Bike{
9. void run(){[Link]("running safely..");}
10. }
11. class TestAbstraction2{
12. public static void main(String args[]){
13. Bike obj = new Honda();
14. [Link]();
15. [Link]();
16. }
17. }

bike is created
running safely..
gear changed

Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
compile time error

Rule: If you are extending any abstract class that have abstract method, you must either
provide the implementation of the method or make this class abstract.

16
Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.

1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){[Link]("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){[Link]("I am a");}
14. public void b(){[Link]("I am b");}
15. public void d(){[Link]("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Output: I am a
I am b
I am c
I am d

17
Interface in Java
 Interface
 Example of Interface
 Multiple inheritance by Interface
 Why multiple inheritance is supported in Interface while it is not supported in case of
class.
 Marker Interface
 Nested Interface

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

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

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

 It is used to achieve fully abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and methods are public and
abstract.

18
Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

19
Simple example of Java interface

In this example, Printable interface have only one method, its implementation is provided in the
A class.
1. interface printable{
2. void print();
3. }
4.
5. class A6 implements printable{
6. public void print(){[Link]("Hello");}
7.
8. public static void main(String args[]){
9. A6 obj = new A6();
10. [Link]();
11. }
12. }

Output: Hello

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.

20
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
8.
9. class A7 implements Printable,Showable{
10.
11. public void print(){[Link]("Hello");}
12. public void show(){[Link]("Welcome");}
13.
14. public static void main(String args[]){
15. A7 obj = new A7();
16. [Link]();
17. [Link]();
18. }
19. }

Output: Hello
Welcome

Q) Multiple inheritance is not supported through class in java but it is possible by


interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in case of

21
class. But it is supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class. For example:

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestTnterface1 implements Printable,Showable{
9. public void print(){[Link]("Hello");}
10. public static void main(String args[]){
11. TestTnterface1 obj = new TestTnterface1();
12. [Link]();
13. }
14. }

Hello

As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance

A class implements interface but one interface extends another interface .

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){[Link]("Hello");}
10. public void show(){[Link]("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. [Link]();
15. [Link]();
16. }
17. }

22
Hello
Welcome

Q) What is marker or tagged interface?

An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to the
JVM so that JVM may perform some useful operation.

1. //How Serializable interface is written?


2. public interface Serializable{
3. }

Nested Interface in Java

Note: An interface can have another interface i.e. known as nested interface. We will learn it in
detail in the nested classes chapter. For example:

1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }

More about Nested Interface

23
Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can have static methods, main Interface can't have static methods, main method or
method and constructor. constructor.

5) Abstract class can provide the Interface can't provide the implementation of abstract class.
implementation of interface.

6) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

24
Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

1. //Creating interface that has 4 methods


2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8.
9. //Creating abstract class that provides the implementation of one method of A interface
10. abstract class B implements A{
11. public void c(){[Link]("I am C");}
12. }
13.
14. //Creating subclass of abstract class, now we need to provide the implementation of rest of the m
ethods
15. class M extends B{
16. public void a(){[Link]("I am a");}
17. public void b(){[Link]("I am b");}
18. public void d(){[Link]("I am d");}
19. }
20.
21. //Creating a test class that calls the methods of A interface
22. class Test5{
23. public static void main(String args[]){
24. A a=new M();
25. a.a();
26. a.b();
27. a.c();
28. a.d();
29. }}

Output:
I am a
I am b
I am c
I am d

25
Java Package
 Java Package
 Example of package
 Accessing package
o By import packagename.*
o By import [Link]
o By fully qualified name
 Subpackage
 Sending class file to another directory
 -classpath switch
 4 ways to load the class file or jar file
 How to put two public class in a package
 Static Import
 Package class

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.

26
Simple example of java package

The package keyword is used to create a package in java.

1. //save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }

How to compile java package

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

1. javac -d directory javafilename

27
For example

1. javac -d . [Link]

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. [Link] etc to run the class.

To Compile: javac -d . [Link]


To Run: java [Link]

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.
1. import package.*;
2. import [Link];
3. 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.

28
Example of package that import the packagename.*

1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. [Link]();
10. }
11. }

Output: Hello

2) Using [Link]

If you import [Link] then only declared class of this package will be accessible.

Example of package by import [Link]

1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1.
1. //save by [Link]
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. [Link]();
10. }

29
11. }

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. [Link] and [Link] packages
contain Date class.

Example of package by import fully qualified name

1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1.
1. //save by [Link]
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name
7. [Link]();
8. }
9. }

Output: Hello

Note: If you import a package, subpackages will not be imported.

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.

30
Note: Sequence of the program must be package then import then class.

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 [Link] e.g. [Link]


or [Link].

Example of Subpackage

1. package [Link];
2. class Simple{
3. public static void main(String args[]){
4. [Link]("Hello subpackage");
5. }

31
6. }
To Compile: javac -d . [Link]
To Run: java [Link]

Output: Hello subpackage

How to send the class file to another directory or drive?

There is a scenario, I want to put the class file of [Link] source file in classes folder of c: drive.
For example:

1. //save as [Link]
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. [Link]("Welcome to package");
7. }
8. }

32
To Compile:

e:\sources> javac -d c:\classes [Link]

To Run:

To run this program from e:\source directory, you need to set classpath of the directory where the
class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java [Link]

Another way to run this program by -classpath switch of java:

The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:

e:\sources> java -classpath c:\classes [Link]

Output: Welcome to package

Ways to load the class files or jar files

There are two ways to load the class files temporary and permanent.

 Temporary
o By setting the classpath in the command prompt
o By -classpath switch
 Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
1. //save as [Link] otherwise Compilte Time Error

33
2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?

If you want to put two public classes in a package, have two java source files containing one
public class, but keep the package name same. For example:

1. //save as [Link]
2.
3. package javatpoint;
4. public class A{}
1. //save as [Link]
2.
3. package javatpoint;
4. public class B{}

What is static import feature of Java5?

Click Static Import feature of Java5.

What about package class?

Click for Package class

34
Access Modifiers in java
 private access modifier
 Role of private constructor
 default access modifier
 protected access modifier
 public access modifier
 Applying access modifier with method overriding

There are two types of modifiers in java: access modifiers and non-access modifiers.

The access modifiers in java specify accessibility (scope) of a data member, method, constructor
or class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.

1) private access modifier

The private access modifier is accessible only within class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is compile time error.
1. class A{
2. private int data=40;
3. private void msg(){[Link]("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
35
9. [Link]([Link]);//Compile Time Error
10. [Link]();//Compile Time Error
11. }
12. }

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

1. class A{
2. private A(){}//private constructor
3. void msg(){[Link]("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }

Note: A class cannot be private or protected except nested class.

2) default access modifier

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

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
1. //save by [Link]
2. package pack;
3. class A{
4. void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;

36
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. [Link]();//Compile Time Error
8. }
9. }

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.

1. //save by [Link]
2. package pack;
3. public class A{
4. protected void msg(){[Link]("Hello");}
5. }

1. //save by [Link]
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. [Link]();
9. }
10. }
Output: Hello

37
4) public access modifier

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

Example of public access modifier

1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. [Link]();
10. }
11. }

Output: Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

38
Java access modifiers with method overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.

1. class A{
2. protected void msg(){[Link]("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){[Link]("Hello java");}//[Link]
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. [Link]();
10. }
11. }

The default modifier is more restrictive than protected. That is why there is compile time error.

39
Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.

We can create a fully encapsulated class in java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of fully encapsulated class.

Advantage of Encapsulation in java

By providing only setter or getter method, you can make the class read-only or write-only.

It provides you the control over the data. Suppose you want to set the value of id i.e. greater
than 100 only, you can write the logic inside the setter method.

Simple example of encapsulation in java

Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.

1. //save as [Link]
2. package [Link];
3. public class Student{
4. private String name;
5.
6. public String getName(){
7. return name;
8. }
9. public void setName(String name){
10. [Link]=name
11. }
12. }
1. //save as [Link]
2. package [Link];
3. class Test{

40
4. public static void main(String[] args){
5. Student s=new Student();
6. [Link]("vijay");
7. [Link]([Link]());
8. }
9. }

Compile By: javac -d . [Link]


Run By: java [Link]
Output: vijay

41
Object class in Java
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, known as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't what object would be returned from this method

The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

42
Methods of Object class

The Object class provides many methods. They are as follows:

Method Description

public final ClassgetClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long timeout)throws causes the current thread to wait for the specified milliseconds,
InterruptedException until another thread notifies (invokes notify() or notifyAll()
method).

public final void wait(long timeout,int causes the current thread to wait for the specified miliseconds
nanos)throws InterruptedException and nanoseconds, until another thread notifies (invokes notify()
or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.

We will have the detailed learning of these methods in next chapters.

43
Object Cloning in Java

The object cloning is a way to create exact copy of an object. For this purpose, clone() method
of Object class is used to clone an object.

The [Link] interface must be implemented by the class whose object clone we
want to create. If we don't implement Cloneable interface, clone() method
generatesCloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

1. protected Object clone() throws CloneNotSupportedException

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If
we perform it by using the new keyword, it will take a lot of processing to be performed that is
why we use object cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)

Let's see the simple example of object cloning

1. class Student18 implements Cloneable{


2. int rollno;
3. String name;

44
4.
5. Student18(int rollno,String name){
6. [Link]=rollno;
7. [Link]=name;
8. }
9.
10. public Object clone()throws CloneNotSupportedException{
11. return [Link]();
12. }
13.
14. public static void main(String args[]){
15. try{
16. Student18 s1=new Student18(101,"amit");
17.
18. Student18 s2=(Student18)[Link]();
19.
20. [Link]([Link]+" "+[Link]);
21. [Link]([Link]+" "+[Link]);
22.
23. }catch(CloneNotSupportedException c){}
24.
25. }
26. }

Output: 101 amit


101 amit

As you can see in the above example, both reference variables have the same value. Thus, the
clone() copies the values of an object to another. So we don't need to write explicit code to copy
the value of an object to another.

If we create another object by new keyword and assign the values of another object to this one, it
will require a lot of processing on this object. So to save the extra processing task we use clone()
method.

45
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is
known as call by value. The changes being done in the called method, is not affected in the
calling method.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. [Link]("before change "+[Link]);
12. [Link](500);
13. [Link]("after change "+[Link]);
14.
15. }
16. }
Output: before change 50
after change 50

Another Example of call by value in java

In case of call by reference original value is changed if we made changes in the called method. If
we pass object in place of any primitive value, original value will be changed. In this example
we are passing object as a value. Let's take a simple example:

1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. [Link]=[Link]+100;//changes will be in the instance variable
6. }
7.

46
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. [Link]("before change "+[Link]);
13. [Link](op);//passing object
14. [Link]("after change "+[Link]);
15.
16. }
17. }
Output: before change 50
after change 150

47
Creating API Document | javadoc tool
We can create document api in java by the help of javadoc tool. In the java file, we must use the
documentation comment /**... */ to post information for the class, method, constructor, fields
etc.

Let's see the simple class that contains documentation comment.

1. package [Link];
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){[Link](n*n*n);}
7. }

To create the document API, you need to use the javadoc tool followed by java file name. There
is no need to compile the javafile.

On the command prompt, you need to write:

javadoc [Link]

to generate the document api. Now, there will be created a lot of html files. Open the [Link]
file to get the information about the classes.

48
Java Command Line Arguments
 Command Line Argument
 Simple example of command-line argument
 Example of command-line argument that prints all the values

The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be used as
an input.

So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java program,
you must pass at least one argument from the command prompt.

1. class CommandLineExample{
2. public static void main(String args[]){
3. [Link]("Your first argument is: "+args[0]);
4. }
5. }

1. compile by > javac [Link]


2. run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument that prints all the values

In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.
1. class A{
2. public static void main(String args[]){
3.

49
4. for(int i=0;i<[Link];i++)
5. [Link](args[i]);
6.
7. }
8. }
1.
1. compile by > javac [Link]
2. run by > java A sonoo jaiswal 1 3 abc

Output: sonoo
jaiswal
1
3
abc

50

You might also like