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

Java UNIT-3

This is the my college notes and references to the hand made notes

Uploaded by

psakshi2129
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java UNIT-3

This is the my college notes and references to the hand made notes

Uploaded by

psakshi2129
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Polymorphism and Packages

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.

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.

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

2) Method Overloading: changing data type of arguments

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

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

Why Method Overloading is not possible by changing the return type of


method only?

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:

Compile Time Error: method add(int,int) is already defined in class Adder

❖ Method Overriding- dynamic method dispatch


Method overriding is one of the ways in which Java supports Runtime
Polymorphism. Dynamic method dispatch is the mechanism by which a call to
an overridden method is resolved at run time, rather than compile time.
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).

MANISHA RAJPUT 3
Polymorphism and Packages

Program:
//Java Program to illustrate the use of Java Method Overriding

//Creating a parent class.

class Vehicle{

//defining a method

void run(){

System.out.println("Vehicle is running");}

//Creating a child class

class Bike2 extends Vehicle{

//defining the same method as in the parent class

void run(){

System.out.println("Bike is running safely");}

public static void main(String args[]){

Bike2 obj = new Bike2(); //creating object

obj.run(); //calling method

Output:
Bike is running safely

❖ Abstract methods and classes Interfaces


Abstraction in Java is the process in which we only show essential
details/functionality to the user. The non-essential implementation details are not
displayed to the user.
Examples: Fan, Car, Bike, etc.

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.

MANISHA RAJPUT 4
Polymorphism and Packages

1. Using abstract Class


Program 1:
abstract class sunstar {

abstract void printInfo();


}

class employee extends sunstar {


void printInfo()
{
String name = "avinash";
int age = 21;
float salary = 222.2F;

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.

Types of Inner Classes


There are basically four types of inner classes in java.
1. Local Inner Classes
2. Static nested Class

MANISHA RAJPUT 6
Polymorphism and Packages

3. Anonymous Inner Classes


4. Member Inner class

Syntax:
class Outer{
//code
class Inner{
//code
}
}

1. Local Inner Classes


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.
Program:
public class localInner1{
private int data=30;//instance variable
void display()
{
class Local
{
void msg()
{
System.out.println(data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}

Output: 30

MANISHA RAJPUT 7
Polymorphism and Packages

2. Static Nested Classes


A static class is a class that is created inside a class, is called a static nested
class in Java. It cannot access non-static data members and methods. It can be
accessed by outer class name.
Program

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

3. Anonymous Inner Classes


Java anonymous inner class is an inner class without a name(no 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.

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

4. Member Inner class


Created inside a class but outside a method(not inside a method). 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.
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output:
data is 30

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

❖ Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with
objects many times like in Collections, Serialization, Synchronization, etc.
Let us see the different scenarios, where we need to use the wrapper classes.

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

Primitive Type Wrapper Class

boolean Boolean

byte Byte

char Character

float Float

int Integer

long Long

short Short

double Double

MANISHA RAJPUT 10
Polymorphism and Packages

➢ Autoboxing

The automatic conversion of primitive data type into its corresponding


wrapper class is known as autoboxing, for example, byte to Byte, char to
Character, int to Integer, long to Long, float to Float, boolean to Boolean, double
to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.

Wrapper class Example: Primitive to Wrapper

//Java program to convert primitive into objects


//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}}

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.

Wrapper class Example: Wrapper to Primitive

/Java program to convert object into primitives


//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);

MANISHA RAJPUT 11
Polymorphism and Packages

int i=a.intValue();//converting Integer to int explicitly


int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}}

Output:

3 3 3

❖ use of Final keyword


The final method in Java is used as a non-access modifier applicable only to
a variable, a method, or a class. It is used to restrict a user in Java.
The following are different contexts where the final is used:

1. Variable
2. Method
3. Class

1) Java final variable


class Bike9{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:
Compile Time Error

MANISHA RAJPUT 12
Polymorphism and Packages

2) Java final method

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

Example of final method

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Output:
Compile Time Error

3) Java final class


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

Example of final class

final class Bike{}

class Honda1 extends Bike


{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:
Compile Time Error

MANISHA RAJPUT 13
Polymorphism and Packages

Is final method inherited?

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

❖ Packages: 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.

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

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.
5. java.awt: Contain classes for implementing the components for
graphical user interfaces (like button , ;menus etc). 6)
6. java.net: Contain classes for supporting networking operations.

❖ 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

5. java.awt: Contain classes for implementing the components for


graphical user interfaces (like button , ;menus etc).
6. java.net: Contain classes for supporting networking operations.

Java. awt package

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

This package provides classes and an interface for handling the


system(input/output). Using these classes programmer can take the input from
the user and do operations on that and then display the output to the user.
Other than this we can also perform file handling read or write using classes of
this package.

• Java

import java.io.Console;

class example_io {

public static void main(String args []) {


Console cons = System.console();
System.out.println("Enter your favorite color");
String colour ;
colour = cons.readLine();
System.out.println("Favorite colour is " + colour);
}
}

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;

public class MyClass {


public static void main(String args[]) {
int[] arr = { 40, 30, 20, 70, 80 };
Arrays.sort(arr);
System.out.printf("Sorted Array is = "+Arrays.toString(arr));
}
}

Output:
Sorted Array is = [20, 30, 40, 70, 80]

❖ Creating user-defined packages


User-defined packages are those packages that are designed or created by
the developer to categorize classes and packages. They are much similar to the
built-in that java offers. It can be imported into other classes and used the
same as we use built-in packages. But If we omit the package statement, the
class names are put into the default package, which has no name.

To create a package, we’re supposed to use the package keyword.


Syntax:
package package-name;

Steps to create User-defined Packages

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
}

Step 3: Now the user-defined package is successfully created, we can import it


into other packages and use its functions it.
Note: If we do not write any class in the package, it will be placed in the
current default package.
In the below-mentioned examples, in the first example we’ll create a user-
defined package name “example” under that we’ve class named “gfg,” which
has a function to print message. In the second example, we will import our
user-defined package name “example” and use a function present in that
package.
Example 1: In this example, we’ll create a user-defined package and function
to print a message for the users.

Program:
// Java program to create a user-defined
// package and function to print
// a message for the users
package example;

// Class
public class gfg{

public void show()


{
System.out.println("Hello all!! How are you?");
}

public static void main(String args[])


{
gfg obj = new gfg();
obj.show();
}
}

Output:
Hello all!! How are you?

MANISHA RAJPUT 19
Polymorphism and Packages

MANISHA RAJPUT 20

You might also like