Java UNIT-3
Java UNIT-3
UNIT – 3
Syllabus
❖ Method Overloading,
❖ Method Overriding- dynamic method dispatch,
❖ Abstract methods and classes Interfaces,
❖ inner classes,
❖ Wrapper Classes,
❖ use of Final keyword
Packages
❖ Packages Concept,
❖ built-in packages-java. Lang. math, java.util.
❖ Creating user-defined packages
❖ Method Overloading
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 the 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.
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.
Program:
class Adder{
static int add(int a,int b)
MANISHA RAJPUT 1
Polymorphism and Packages
{
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
In this example, we have created two methods that differs in data type. The first
add method receives two integer arguments and second add method receives two
double arguments.
Program:
class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
MANISHA RAJPUT 2
Polymorphism and Packages
Output:
1. 22
2. 24.9
In java, method overloading is not possible by changing the return type of the
method only because of ambiguity. Let's see how ambiguity may occur:
Program
class Adder{
static int add(int a,int b)
{
return a+b;
}
static double add(int a,int b)
{
return a+b;
}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
MANISHA RAJPUT 3
Polymorphism and Packages
Program:
//Java Program to illustrate the use of Java Method Overriding
class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");}
void run(){
Output:
Bike is running safely
MANISHA RAJPUT 4
Polymorphism and Packages
System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}
class base {
public static void main(String args[])
{
sunstar s = new employee();
s.printInfo();
}
}
Output
avinash
21
222.2
2. Using Interface
Program 2:
//Creating interface that has 4 methods
MANISHA RAJPUT 5
Polymorphism and Packages
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal
{
public void animalSound()
{
System.out.println("The pig says: wee wee");
}
public void sleep() {
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output:
The pig says: wee wee
Zzz
❖ Inner classes
In Java, it is also possible to nest classes (a class within a class). The purpose
of nested classes is to group classes that belong together, which makes your
code more readable and maintainable.
There are certain advantages associated with inner classes are as follows:
• Making code clean and readable.
• Private methods of the outer class can be accessed, so bringing a new
dimension and making it closer to the real world.
• Optimizing the code module.
MANISHA RAJPUT 6
Polymorphism and Packages
Syntax:
class Outer{
//code
class Inner{
//code
}
}
Output: 30
MANISHA RAJPUT 7
Polymorphism and Packages
class TestOuter1{
static int data=30;
static class Inner{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
Program:
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
MANISHA RAJPUT 8
Polymorphism and Packages
void eat()
{
System.out.println("nice fruits");
}
};
p.eat();
}
}
Output:
nice fruits
❖ Wrapper Classes
The wrapper class in Java provides the mechanism to convert primitive
into object and object into primitive.
MANISHA RAJPUT 9
Polymorphism and Packages
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and vice-
versa unboxing.
• Change the value in Method: Java supports only call by value. So,
if we pass a primitive value, it will not change the original value. But,
if we convert the primitive value in an object, it will change the
original value.
• Serialization: We need to convert the objects into streams to perform
the serialization. If we have a primitive value, we can convert it in
objects through the wrapper classes.
• Synchronization: Java synchronization works with objects in
Multithreading.
• java.util package: The java.util package provides the utility classes
to deal with objects.
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
MANISHA RAJPUT 10
Polymorphism and Packages
➢ Autoboxing
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
Output:
20 20 20
➢ Unboxing
The automatic conversion of wrapper type into its corresponding primitive type
is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we
do not need to use the intValue() method of wrapper classes to convert the
wrapper type into primitives.
MANISHA RAJPUT 11
Polymorphism and Packages
Output:
3 3 3
1. Variable
2. Method
3. Class
Output:
Compile Time Error
MANISHA RAJPUT 12
Polymorphism and Packages
class Bike{
final void run(){System.out.println("running");}
}
Output:
Compile Time Error
MANISHA RAJPUT 13
Polymorphism and Packages
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run()
{
System.out.println("running...");
}
}
class Honda2 extends Bike
{
public static void main(String args[]){
new Honda2().run();
}
}
Output: running..
• 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.
Types of packages:
➢ Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
MANISHA RAJPUT 14
Polymorphism and Packages
❖ Built-in packages
Packages that come with JDK or JRD you download are known as built-in
packages. The built-in packages have come in the form of JAR files and when
we unzip the JAR files we can easily see the packages in JAR files, for example,
lang, io, util, SQL, etc. Java provides various built-in packages for
example java.awt
➢ Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
1. java.lang: Contains language support classes(e.g classes which defines
primitive data types, math operations). This package is automatically
imported.
2. java.io: Contains classes for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like
Linked List, Dictionary and support ; for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
MANISHA RAJPUT 15
Polymorphism and Packages
This package is the main package of the abstract window kit. it includes the
classes for graphics, containing the java 2D graphics and it also defines the
graphical user interface(GUI) framework for java. this package had several heavy
GUI objects which come under java. swing package.
Java.net package
This package contains the classes and interfaces for networking like Socket
class, ServerSocket class, URLConnection class, DatagramSocket,
MulticastSocket, etc. Java supports the two network protocols such as
TCP(Transmission control protocol) and UDP(User Datagram Protocol which
is a connection-less protocol).
java.sql package
This package contains the classes and interfaces to provide and perform all
JDBC tasks like creating and executing SQL queries. It includes a framework
where different drivers can be installed dynamically to access different-different
databases and it also provides the API for accessing and processing the database
which is stored in a database.
java.lang package
This package contains the core classes of the java language. This package is
automatically imported to each program, which means we can directly use
classes of this package in our program. Let’s have an example of the Math
class of lang package which provides various functions or methods for
mathematical operation.
• Java
import java.lang.*;
class example_lang {
public static void main(String args []) {
int a = 100, b = 200,maxi;
MANISHA RAJPUT 16
Polymorphism and Packages
maxi = Math.max(a,b);
System.out.printf("Maximum is = "+maxi);
}
}
Output
Maximum is = 200
java.io package
• Java
import java.io.Console;
class example_io {
Output
Enter your favorite color
RED
Favorite color is RED
java.util package
This package provides the basic necessary things to java programmers. The
most common class in this package is Arrays which is generally used by
programmers in various cases. we can say that it is the most useful package for
java because it helps to achieve different types of requirements easily by using
pre-written classes. let’s see the example of Arrays class.
MANISHA RAJPUT 17
Polymorphism and Packages
• Java
import java.util.Arrays;
Output:
Sorted Array is = [20, 30, 40, 70, 80]
Step 1: Creating a package in java class. The format is very simple and easy.
Just write a package by following its name.
package example1;
Step 2: Include class in java package, But remember that class only has one
package declaration.
package example1;
class gfg {
public static void main(Strings[] args){
-------function--------
}
MANISHA RAJPUT 18
Polymorphism and Packages
}
Program:
// Java program to create a user-defined
// package and function to print
// a message for the users
package example;
// Class
public class gfg{
Output:
Hello all!! How are you?
MANISHA RAJPUT 19
Polymorphism and Packages
MANISHA RAJPUT 20