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

Java UNIT-1

Uploaded by

Bindu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Java UNIT-1

Uploaded by

Bindu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

UNIT-I

A computer program is a set of instructions that instruct the CPU to perform a


defined task. We can write computer programs using various programming
languages. Furthermore, a programming paradigm is a way of categorizing a
programming language depending on its features. Two such paradigms are
structured and object oriented programming.

What is Structured Programming


Structured Programming divides a program into a set of functions or
modules. Modular programming is another name for this. These functions have
statements embraced inside curly braces. Each of these functions performs a
subtask. Usually, as each function represents a specific functionality, it is easier
for the programmer to test and debug the code, but this can differ depending on
the program. C language and Pascal are two common structured programming
languages.

In the structured programming C, the user can create his own user-defined
functions. The main function calls the other functions. It indicates the execution
of the program. When there is a function call, the control is passed to that
function. After completing the function, the control passes back to the main
program. Moreover, a variable inside a function is a local variable, and global
variables are accessible by all the functions.

What is Object Oriented Programming?


Object oriented programming allows the programmer to represent real-world
scenarios using objects. An object is any entity that has states and behaviours.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
States represent the attributes or data of an object, whereas the methods
represent the behaviours of objects. Student, Employee, Book etc. are objects.
These objects interact with other objects by passing messages. Furthermore,
a class is a blueprint for creating an object. It is necessary to have a class to create
objects. For example, to create an Employee object, there should be an Employee
class.

Difference Between Structured and Object Oriented Programming


Definition
Structured programming is a programming paradigm which divides the code into
modules or function, while OOP is a programming paradigm based on the concept
of objects, which contain data in the form of fields known as attributes, and code
in the form of procedures known as methods. Thus, this explains the main
difference between structured and object oriented programming.

Main Focus

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Furthermore, structured programming focuses on dividing the program into a set
of functions in which each function works as a subprogram while object oriented
programming focuses on representing a program using a set of objects which
encapsulates data and object.

Modification
Moreover, it is difficult to modify the structured programs while it is easier to
modify the Object Oriented programs.

Communication
In structured programming, the main method communicates with the functions
by calling those functions in the main program whereas, in object oriented
programming, the objects communicate with each other by passing messages.
Hence, this is an important difference between structured and object oriented
programming.

Access Specifiers
There are no access specifiers in structured programming while there are access
specifiers such as private, public and protected in Object Oriented Programming.
Thus, this is also an important difference between structured and object oriented
programming.

Security
Besides, data is not secure in structured programming, but it is secure in object
oriented programming.

Code Reusability
Also, it is difficult to reuse code in structured programming, whereas it is easier to
reuse code in object oriented programming.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Features of Java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are
also some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10.Multithreaded

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
11.Distributed
12.Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:

o Java syntax is based on C++ (so easier for programmers to learn it after C+
+).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different
types of objects that incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Platform Independent

Java is platform independent because it is different from other languages


like C, C++, etc. which are compiled into platform specific machines while Java is a
write once, run anywhere language. A platform is the hardware or software
environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java


provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on top of other hardware-based platforms. It
has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted
into bytecode. This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Secured

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment


(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of
the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
o Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.

Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
etc.

Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent


features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit


architecture and 4 bytes of memory for 64-bit architecture. However, it occupies
4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.

High-performance

Java is faster than other traditional interpreted programming languages because


Java bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed applications in


Java. RMI and EJB are used for creating distributed applications. This feature of
Java makes us able to access files by calling the methods from any machine on the
internet.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java


programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.

Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means


classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.

The main aim of object-oriented programming is to implement real-world entities,


for example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Object

Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address


and takes up some space in memory. Objects can communicate without knowing
the details of each other's data or code. The only necessary thing is the type of
message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.

Inheritance

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For


example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve


polymorphism.

Another example can be to speak something; for example, a cat speaks meow,
dog barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For


example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Encapsulation

Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.

Class:
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:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Object:
An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and intangible).
The example of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.

An object is an instance of a class. A class is a template or blueprint from which


objects are created. So, an object is the instance(result) of a class.
Using new Keyword

Using the new keyword is the most popular way to create an object or instance of
the class. When we create an instance of the class by using the new keyword, it
allocates memory (heap) for the newly created object and also returns
the reference of that object to that memory. The new keyword is also used to
create an array. The syntax for creating an object is:

1. ClassName object = new ClassName();


3 Ways to initialize object

There are 3 ways to initialize object in Java.

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

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
1) Object and Class Example: Initialization through reference

1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12.}
Test it Now

Output:

101 Sonoo

2) Object and Class Example: Initialization through method

1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10.class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19.}
Test it Now

Output:

111 Karan
222 Aryan

As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area.
Here, s1 and s2 both are reference variables that refer to the objects allocated in
memory.

3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later.

1. class Employee{
2. int id;
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11.}
12.public class TestEmployee {
13.public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23.}
24.}
Test it Now

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java:
local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable

A variable is the name of a reserved area allocated in memory. In other words, it


is a name of the memory location. It is a combination of "vary + able" which
means its value can be changed.

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
It is called an instance variable because its value is instance-specific and is not
shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local.


You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.

Instance Method

The method of the class is known as an instance method. It is a non-


static method defined in the class. Before calling or invoking the instance method,
it is necessary to create an object of its class. Let's see an example of an instance
method.

Method in Java
In Java, a method is like a function which is used to expose the behavior of an
object.

Advantage of Method
o Code Reusability

o Code Optimization

Method Declaration

The method declaration provides information about method attributes, such as


visibility, return-type, name, and arguments. It has six components that are
known as method header, as we have shown in the following figure.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method

In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as the standard
library method or built-in method. We can directly use these methods just by
calling them in the program at any point. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in
our program, a series of codes related to the corresponding method runs in the
background that is already stored in the library.

Each and every predefined method is defined inside a class. Such


as print() method is defined in the java.io.PrintStream class. It prints the
statement that we write inside the method. For example, print("Java"), it prints
Java on the console.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.

If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you
as well as other programmers to understand the behavior of the method because
its name differs.

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

In Java, Method Overloading is not possible by changing the return type of the
method only.

1) Method Overloading: changing no. 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.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now

Output:

22
33

Constructors in Java
a constructor is a block of codes similar to the method. It is called when an
instance of the class
is created. At the time of calling constructor, memory for the object is allocated in
the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor
is called.

It calls a default constructor if there is no constructor available in the class. In


such case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and


parameterized constructor.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers


while declaring a constructor. It controls the object creation. In other words, we
can have private, protected, public or default constructor in Java.

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

1. <class_name>(){}

2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10.}
Test it Now
Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a


parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct


objects. However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


1. class Student4{
2. int id;
3. String name;
4. //creating a parameterized constructor
5. Student4(int i,String n){
6. id = i;
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
7. name = n;
8. }
9. //method to display the values
10. void display(){System.out.println(id+" "+name);}
11.
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20.}

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.

Constructor overloading in Java

is a technique of having more than one constructor with different parameter lists.
They are arranged in a way that each constructor performs a different task. They
are differentiated by the compiler by the number of parameters in the list and
their types.

Example of Constructor Overloading

//Java program to overload constructors


1. class Student5{
2. int id;
3. String name;
4. int age;
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
5. //creating two arg constructor
6. Student5(int i,String n){
7. id = i;
8. name = n;
9. }
10. //creating three arg constructor
11. Student5(int i,String n,int a){
12. id = i;
13. name = n;
14. age=a;
15. }
16. void display(){System.out.println(id+" "+name+" "+age);}
17.
18. public static void main(String args[]){
19. Student5 s1 = new Student5(111,"Karan");
20. Student5 s2 = new Student5(222,"Aryan",25);
21. s1.display();
22. s2.display();
23. }
24.}

1111,"Karan 11 K’
222,"Aryan",25a

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

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 the parent class. Moreover, you can add new methods and
fields in your current class also.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.

The 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 a parent or


superclass, and the new class is called child or subclass.

Java Inheritance Example

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A
Employee. It means that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10.}
11.}
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
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.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the single
inheritance.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}

Output:

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you


can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10.class TestInheritance2{
11.public static void main(String args[]){
12.BabyDog d=new BabyDog();
13.d.weep();
14.d.bark();
15.d.eat();
16.}}

Output:

weeping...
barking...
eating...

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and
B classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or different,
there will be compile time error.

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method


that has been declared by one of its parent class, it is known as method
overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Example of method overriding

In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of
the method are the same, and there is IS-A relationship between the classes, so
there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16.}
Test it Now

Output:

Bike is running safely

Polymorphism in Java
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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
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 a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Compile-time Polymorphism
Compile-time polymorphism is also known as static polymorphism or early
binding. Compile-time polymorphism is a polymorphism that is resolved during
the compilation process. Overloading of methods is called through the reference
variable of a class. Compile-time polymorphism is achieved by method
overloading and operator overloading.

1. Method overloading
We can have one or more methods with the same name that are solely
distinguishable by argument numbers, type, or order.
Method Overloading occurs when a class has many methods with the same
name but different parameters. Two or more methods may have the same name
if they have other numbers of parameters, different data types, or different
numbers of parameters and different data types.

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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.

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.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

Suggestion: If you are beginner to java, lookup only three usages of this keyword.

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.

1. class Student{
2. int rollno;

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while
invoking the method. Let's see the example

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.

3) Real usage of this() constructor call(Constructor chaining)

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
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.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10.Student(int rollno,String name,String course,float fee){
11.this(rollno,name,course);//reusing constructor
12.this.fee=fee;
13.}
14.void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15.}
16.class TestThis7{
17.public static void main(String args[]){
18.Student s1=new Student(111,"ankit","java");
19.Student s2=new Student(112,"sumit","java",6000f);
20.s1.display();
21.s2.display();
22.}}
Test it Now

Output:

111 ankit java 0.0


112 sumit java 6000.0
Rule: Call to this() must be the first statement in constructor.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Super Keyword in Java
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.

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 {
protected String type="animal";
}

class Dog extends Animal {


public String type="mammal";

public void printType() {


System.out.println("I am a " + type);
System.out.println("I am an " + super.type);
}
}

class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printType();
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
}
}
Run Code
Output:

I am a mammal
I am an animal

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 {

// overridden method
public void display(){
System.out.println("I am an animal");
}
}

class Dog extends Animal {

// overriding method
@Override
public void display(){
System.out.println("I am a dog");
}

public void printMessage(){

// this calls overriding method


display();

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
// this calls overridden method
super.display();
}
}

class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printMessage();
}
}
Run Code
Output

I am a dog
I am an animal

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

class Animal {

// default or no-arg constructor of class Animal


Animal() {
System.out.println("I am an animal");
}
}

class Dog extends Animal {

// default or no-arg constructor of class Dog


Dog() {

// calling default constructor of the superclass


Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
super();

System.out.println("I am a dog");
}
}

class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
Run Code
Output

I am an animal
I am a dog

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only. We will have detailed learning of these.
Let's first learn the basics of final keyword.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It
will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can
never be changed.

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

// create a final variable


final int AGE = 32;

// try to change the final variable


AGE = 45;
System.out.println("Age: " + AGE);
}
}

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
2) Java final method

If you make any method as final, you cannot override it.

class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}

class Main extends FinalDemo {


// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}
3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

final class FinalClass {


public void display() {
System.out.println("This is a final method.");
}
}

// try to extend the final class


Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}
When we run the program, we will get a compilation error with the following
message.

cannot inherit from final FinalClass


class Main extends FinalClass {
^

Java static keyword


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

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable

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


Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).


Understanding the problem without static variable
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will
get memory each time when the object is created. All students have its unique
rollno and name, so instance data member is good in such case. Here, "college"
refers to the common property of all objects. If we make it static, this field will get
the memory only once.

Java static property is shared to all objects.

Example of static variable

1. //Java Program to demonstrate the use of static variable


2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.}
14.//Test class to show the values of objects
15.public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24.}
Test it Now

Output:

111 Karan ITS


222 Aryan ITS

2) Java static method

If you apply static keyword with any method, it is known as static method.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance
of a class.
o A static method can access static data member and can change the value of
it.

Example of static method

1. //Java Program to demonstrate the use of a static method.


2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17.}
18.//Test class to create and display the values of object
19.public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
28. s2.display();
29. s3.display();
30. }
31.}
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Java abstract Keyword


The abstract keyword is used to achieve abstraction in Java. It is a non-access
modifier which is used to create abstract class and method.

The role of an abstract class is to contain abstract methods. However, it may also
contain non-abstract methods. The method which is declared with abstract
keyword and doesn't have any implementation is known as an abstract method.

Syntax:-

1. abstract class Employee


2. {
3. abstract void work();
4. }
Note - We cannot declare abstract methods in non abstract class.
Rules of abstract keyword

Don'ts

o An abstract keyword cannot be used with variables and constructors.


o If a class is abstract, it cannot be instantiated.
o If a method is abstract, it doesn't contain the body.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
o We cannot use the abstract keyword with the final.
o We cannot declare abstract methods as private.
o We cannot declare abstract methods as static.
o An abstract method can't be synchronized.

Do's

o An abstract keyword can only be used with class and method.


o An abstract class can contain constructors and static methods.
o If a class extends the abstract class, it must also implement at least one of
the abstract method.
o An abstract class can contain the main method and the final method.
o An abstract class can contain overloaded abstract methods.
o We can declare the local inner class as abstract.
o We can declare the abstract method with a throw clause.

Examples of abstract Keyword

Example 1: Abstract class containing the abstract method

1. abstract class Vehicle


2. {
3. abstract void bike();
4.
5. }
6. class Honda extends Vehicle
7. {
8.
9. @Override
10. void bike() {
11. System.out.println("Bike is running");
12.
13. }
14.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
15.}
16.
17.public class AbstractExample1 {
18.
19. public static void main(String[] args) {
20.
21. Honda obj=new Honda();
22. obj.bike();
23. }
24.}
Test it Now

Output:

Bike is running

Interface in Java
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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Since Java 9, we can have private methods in an interface.

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

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.

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:

1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
The 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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Java Interface Example

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

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11.}
Test it Now

Output:

Hello

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11.public static void main(String args[]){
12.A7 obj = new A7();
13.obj.print();
14.obj.show();
15. }
16.}
Test it Now
Output:Hello
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Welcome

Java Inner Classes (Nested Classes)


Java inner class or nested class is a class that is declared inside the class or
interface.

We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.

Additionally, it can access all the members of the outer class, including private
data members and methods.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of Java inner classes

There are three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it can


access all the members (data members and methods) of the outer
class, including private.
2. Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Need of Java Inner class

Sometimes users need to program a class in such a way so that no other class can
access it. Therefore, it would be better if you include it within other classes.

If all the class objects are a part of the outer object then it is easier to nest that
class inside the outer class. That way all the outer class can access all the objects
of the inner class.

Difference between nested class and inner class in Java

An inner class is a part of a nested class. Non-static nested classes are known as
inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes. The
non-static nested classes are also known as inner classes.

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

Java Member Inner class

A non-static class that is created inside a class but outside a method is


called member inner class. It is also known as a regular inner class. It can be
declared with access modifiers like public, default, private, and protected.

Syntax:

1. class Outer{
2. //code
3. class Inner{
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
4. //code
5. }
6. }

1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11.}
Test it Now

Output:

data is 30

How to instantiate Member Inner class in Java?

An object or instance of a member's inner class always exists within an object of


its outer class. The new operator is used to create the object of member inner
class with slightly different syntax.

The general form of syntax to create an object of the member inner class is as
follows:

Syntax:

1. OuterClassReference.new MemberInnerClassConstructor();

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Example:

1. obj.new Inner();

Here, OuterClassReference is the reference of the outer class followed by a dot


which is followed by the new operator.

Java Anonymous inner class

Java anonymous inner class is an inner class without a name and for which only a
single object is created. An anonymous inner class can be useful when making an
instance of an object with certain "extras" such as overloading methods of a class
or interface, without having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class
in Java. It should be used if you have to override a method of class or interface.
Java Anonymous inner class can be created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class

TestAnonymousInner.java

1. abstract class Person{


2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11.}
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Output:

nice fruits

Java Local inner class

A class i.e., created inside a method, is called local inner class in java. Local Inner
Classes are the inner classes that are defined inside a block. Generally, this block
is a method body. Sometimes this block can be a for loop, or an if clause. Local
Inner classes are not a member of any enclosing classes. They belong to the block
they are defined within, due to which local inner classes cannot have any access
modifiers associated with them. However, they can be marked as final or abstract.
These classes have access to the fields of the class enclosing it.

If you want to invoke the methods of the local inner class, you must instantiate
this class inside the method.

Java local inner class example

LocalInner1.java

1. public class localInner1{


2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. localInner1 obj=new localInner1();
12. obj.display();
13. }
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
14.}
Output:
30

In such a case, the compiler creates a class named Simple$1Local that has the
reference of the outer class.

Java Package
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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Simple example of java package

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

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("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


Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
For example

1. javac -d . Simple.java

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

1. import package.*;
2. import package.classname;
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.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
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


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
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


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT

You might also like