0% found this document useful (0 votes)
9 views14 pages

Understanding Java Polymorphism Concepts

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

Understanding Java Polymorphism Concepts

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

Java material for B.

sc

UNIT-3
What is polymorphism? Explain polymorphism with variable?
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. 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.
Polymorphism with variables
When using variables sometimes in inherently the data type of the result is decided By the
compiler and accordingly execution proceeds
[Link](a+b);
Java compiler decided the data types of the result of expression a + b depending on the data
type of a and b If a and b are int type ,Then a + b will also be taken as int type If a and b are
floor to type variables then a + b will be taken as float type If a is int and b is float ,Then the
compiler convert a also into float and then Sum is found ,Does the result of a + b is exhibiting
polymorphic nature It may exist as an int or as a float or as some otherData type depending
on the context
Explain polymorphism using methods?
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 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.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
Method overloading increases the readability of the program.
class MethodOverload
{
public Static viod first()
{
[Link]("without any arguments");
}
}
public Static viod first(int a,int b)
{
[Link](a+b);
}
public static void main(string args[])

GD BADESAB Page 1
Java material for [Link]

{
first();
first(10,20);
}
Method Overriding
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
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
class simple
{
public viod display()
{
[Link]("overriding methods");
}
}
class override extends simple
{
public viod display()
{
[Link]();
[Link]("overriding simple methods");
}
}

class Override
{
public static void main(string args[])
{
override obj=new override();
[Link]();
}
}

GD BADESAB Page 2
Java material for [Link]

Explain about polymorphism with static methods?

A static method is a method whose single copy in memory is shared by all the object of the
class Static methods belongs to the Class rather than to the objects So they are also called
class methods When static methods are overloaded or overridden, Since they do not depend
on the objects the java compiler need not wait till the objects are created to understand which
method is called. Polymorphism with static method
Class one
{
Static void calculate()
{
[Link](“square value=” +(x*x));
}
}
Class two extends one
{
Static void calculate()
{
[Link](“square root=” +[Link](x));
}
}
Class poly
{
Public static void main(String args[])
{

One o=new two();


[Link](25);
}
}

Explain about polymorphism with private methods?


Polymorphism with private methods
Private methods are the methods which are declared by using the access specifiers private
This access specifier make the method not to be available outside the class So other
programmers cannot access the private methods Even private methods are not available in the
subclasses This means there is no possibility to override the private methods of the superclass
in its subclasses . Show only method overloading is possible in case of private methods
The only way to call the private methods of a class is by calling them within the class For this
purpose we should create a public method and call the private methods from Within it when
this public method is called it called the private method

GD BADESAB Page 3
Java material for [Link]

Explain Final variables?or polymorphism with final methods?


Final Variable:
Final variable value can never change when the program executed it is similar to constant. A final
keyword can be used to the variable that variable value maintains the fixed value throughout the
entire program.
Ex: final double PI = 3.14;
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}//end of class

Final Method:
Making a method final ensures that the functionality defined in this method will never be altered in
any way. That is this functions cannot be overridden by derived classes.
final void show()
{
------
------
}
class Bike{
final void run(){[Link]("running");}
}

class Honda extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
[Link]();
}
}
Final classes: A class that cannot be sub classed or it cannot be inherited by any other classes, the
class should be defined as final class.
Ex:
final class Aclass
{
Variables;
Methods;
}

GD BADESAB Page 4
Java material for [Link]

final class Bike{}


class Honda1 extends Bike{
void run(){[Link]("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
[Link]();
}
}
Explain about type casting primitive data types?
Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
o Widening Type Casting
o Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.
[Link]
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type 76 | P a g e

float z = y;
[Link]("Before conversion, int value "+x);
[Link]("After conversion, long value "+y);
[Link]("After conversion, float value "+z);
}
}

GD BADESAB Page 5
Java material for [Link]

Narrowing Type Casting


Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not
perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into
int type.
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
[Link]("Before conversion: "+d);
//fractional part lost
[Link]("After conversion into long type: "+l);
//fractional part lost
[Link]("After conversion into int type: "+i);
}
}
Explain casting referenced data types?
You can cast the reference(object) of one (class) type to other
widening in Referenced data types:
we take class One as super class and class Two is its sub class. We do widening by using super
class reference to refer to sub class object. In this case ,we convert the sub class object type as
super class type.
Example:
class One
{
void show1()
{
[Link](“super class”);
}
}
class Two extends One
{
void show2()
{
[Link](“sub class”);
}

GD BADESAB Page 6
Java material for [Link]

class pyk
{
public static void main(String args[])
{
One x;
X=(One) new Two();
x.show1();
}
}
Narrowing in Referenced data types:
Converting super class type into sub class type.
class One
{
void show1()
{
[Link](“super class”);
}
}
class Two extends One
{
void show2()
{
[Link](“sub class”);
}
class pyk
{
public static void main(String args[])
{
Two x;
X=(Two) new One(); 78 | P a g e

x.show1();
}
}
Explain about object class with example?
There is a class with name ‘Object’ in [Link] package which is the super class of all classes.
Object class has below methods
toString() Method.-> returns the String representation of the object.
hashCode() Method.-> is a Java Integer class method which returns the hash code for the given
inputs.
equals(Object obj) Method.-> compares two strings, and returns true if the strings are equal,
and false if not
getClass() method.-> returns the runtime class of this object.

GD BADESAB Page 7
Java material for [Link]

finalize() method.->T his method is called just before an object is garbage collected. finalize()
method overrides to dispose system resources, perform clean-up activities and minimize
memory leaks.
clone() method.-> in Java ... Object cloning refers to the creation of an exact copy of an object.
It creates a new instance of the class
wait(), -> is a part of [Link] class. When wait() method is called, the calling thread
stops its execution until notify()
notify()-> If many threads are waiting on this object
notifyAll() Methods.->this method sends a notification for all waiting threads for the object.

Explain about Abstract class and Abstract methods in Java?


Abstract class:
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
Abstract Method :
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Abstract keyword is used to declare the method as abstract
You have to place the abstract keyword before the method name in the method declaration
an abstract method contain a method signature but no method body
Instead of curly braces the abstract method will have a; At the end
Example of abstract method
abstract void printStatus();
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[])

GD BADESAB Page 8
Java material for [Link]

{
Bank b;
b=new SBI();
[Link]("Rate of Interest is: "+[Link]()+" %");
b=new PNB();
[Link]("Rate of Interest is: "+[Link]()+" %");
}
}
Explain about interface in java?
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
Syntax:
interface <interface_name>{

declare constant fields


declare methods that abstract
by default.
}
An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}

GD BADESAB Page 9
Java material for [Link]

class TestInterface2
{
public static void main(String[] args){
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}
}
How to implement the concept of Multiple inheritance using interface?
In multiple inheritance subclasses are derived from multiple superclasses if Two super classes
have same name for their members( variables and methods )then which member is inherited
into the subclass in the main confusion in multiple inheritance This confusion is reduced by
using multiple interfaces the achieve multiple inheritance
interface Printable
{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
[Link]();
[Link]();
}
}

Define package?Explain types of 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.

GD BADESAB Page 10
Java material for [Link]

Types of packages:

Built-in Packages
These packages consist of a large number of classes which are a part of Java [Link] of the
commonly used built-in packages are:
1) [Link]: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) [Link]: Contains classed for supporting input / output operations.
3) [Link]: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) [Link]: Contains classes for creating Applets.
5) [Link]: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6) [Link]: Contain classes for supporting networking operations.
User-defined packages
creating a package
 Declare the package at beginning of a file using the form package package name
 Define the class that is to be put in the package and declared it public.
 Create a subdirectory under the directory where the main source files are stored .
 Store the listing as the class name . java File in the subdirectory created. Compile the
[Link] creates . class file in the subdirectory.
 These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.

package myPackage;
public class MyClass
{
public void getNames(String s)
{
[Link](s);
}
}
javac -d directory javafilename
javac -d . [Link]
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */

GD BADESAB Page 11
Java material for [Link]

import [Link];

public class PrintName


{
public static void main(String args[])
{
String name = "hello";
MyClass obj = new MyClass();
[Link](name);
}
}
Note : [Link] must be saved inside the myPackage directory since it is a part of the
package.
How to create a JAR file in package?
JAR files are packaged with the ZIP file format, so you can use them for tasks such as lossless
data compression, archiving, decompression, and archive unpacking. These tasks are among the
most common uses of JAR files, and you can realize many JAR file benefits using only these
basic features.
Even if you want to take advantage of advanced functionality provided by the JAR file format
such as electronic signing, you'll first need to become familiar with the fundamental operations.
To perform basic tasks with JAR files, you use the Java Archive Tool provided as part of the Java
Development Kit (JDK). Because the Java Archive tool is invoked by using the jar command, this
tutorial refers to it as 'the Jar tool'.
This section shows you how to perform the most common JAR-file operations, with examples
for each of the basic features:
Creating a JAR File
This section shows you how to use the Jar tool to package files and directories into a JAR file.
Viewing the Contents of a JAR File
You can display a JAR file's table of contents to see what it contains without actually unpacking
the JAR file.
Extracting the Contents of a JAR File
You can use the Jar tool to unpack a JAR file. When extracting files, the Jar tool makes copies of
the desired files and writes them to the current directory, reproducing the directory structure
that the files have in the archive.
Updating a JAR File
This section shows you how to update the contents of an existing JAR file by modifying its
manifest or by adding files.
Running JAR-Packaged Software
This section shows you how to invoke and run applets and applications that are packaged in JAR
files.

GD BADESAB Page 12
Java material for [Link]

Explain about interface in a package?


It is also possible to write interface in package but whenever we create an interface the
implementation classes are also should be created we cannot create an object to the interface
but we can create objects for implementation classes and use them.
package mypack;
public interface MyDate
{
void showDate();
}

Output:
Compile C:\> javac –[Link]

package [Link];
import [Link].*;
public class DateImp1 implements MyDate
{
public void showDate()
{
Date d=new Date();
[Link](d);
}
}

Compile:C:\> javac –[Link]

importnmypack.DateImp1;
class DateDisplay
{
public static void main(String args[])
{
DateImp1 obj=new DateImp1();
[Link]();
}
}
Compile: C:\> javac [Link]
Run:Java DateDisplay

How to creating sub package in a package?


Creating subpackage in package We can create subpackage in the package in the format
package pack1.pack2;
Here We are creating pack2 Which is created inside pack1 To use the classes and interfaces of
pack2 We can write import statements as

GD BADESAB Page 13
Java material for [Link]

import pack1.pack2;
This concept can be extended to create several sub packages in the following program we are
creating teck package inside dream package by writing the statement
package [Link];
package [Link];
public class Sample
{
public void Show()
{
[Link]("welcome to Dreamtech");
}
}
Compile: javac –[Link]
import [Link];
class Use
{
public static void main(String args[])
{
Sample obj=new Sample();
[Link]();
}
}

Compile: javac [Link]


Run: Java Use

How to create API document in java?


For complete application development, developers need to work with third-party code. Now, in
order to integrate the applications with the third-party code, programmers need well-written
documentation, in other words, API documentation.
It is a set of predefined rules and specifications that need to be followed by the programmer to
use the services and resources provided by another software program.
By using the "javadoc" tool we can create a documented API in Java. In the Java file, we must
use the documentation comment /**......*/ to post information for the class, constructors, field,
method, etcetera.
The javadoc tool converts declarations and doc comments in Java source files and formats the
public and protected API into a set of HTML pages.
In general, it creates a list of classes, a class hierarchy and an index of the entire API. As we pass
arguments to javadoc, javadoc produces HTML pages by default for that.

GD BADESAB Page 14

Common questions

Powered by AI

Interfaces in Java are crucial for achieving polymorphism, especially in enabling a form of multiple inheritance. Since Java classes cannot inherit from more than one class, interfaces offer a way to implement multiple behavior contracts. By implementing multiple interfaces, a class can inherit abstract methods from different sources, allowing for polymorphic interfaces while avoiding the diamond problem that plagued multiple inheritance in other languages. This mechanism allows for flexibility and modular design where classes can present different behaviors through interfaces without directly inheriting code from multiple classes .

JAR files in Java are significant as they package multiple files into a singular entity, enabling easier distribution and deployment of software, including application classes and resources. In terms of polymorphism, JAR files can include interfaces and abstract classes that define polymorphic behavior, promoting reuse and modular design across different software systems. Through JAR files, developers encapsulate code libraries that can be utilized polymorphically by other Java programs, enhancing flexibility and functionality .

Java packages organize classes, interfaces, and sub-packages into namespaces, which aids in categorization, access protection, and naming conflict prevention. By grouping associated classes and interfaces, packages make it easier to manage and use large code bases. They contribute to polymorphism by enabling the structured use of interfaces and abstract classes within packages, facilitating coherent and organized polymorphic designs across different parts of a program .

Type casting in Java is related to polymorphism through the concepts of widening and narrowing conversions. Widening conversion refers to upcasting, where a subclass object reference is assigned to a superclass reference, allowing polymorphic behavior where a method may execute differently based on the object's actual type at runtime. Narrowing conversion, or downcasting, conversely involves casting a superclass reference back to a subclass object, which can sometimes be necessary to access subclass-specific methods. These conversions support polymorphic actions, although they must be managed carefully to avoid runtime exceptions .

Polymorphism with variables in Java involves the compiler deciding the data type of the result based on the operands involved in an expression. For instance, in the expression 'a + b,' if 'a' and 'b' are both integers, the result is also treated as an integer. However, if 'a' is an integer and 'b' is a float, the compiler converts 'a' to a float so that the operation results in a float. This showcases polymorphic behavior as the resultant data type adapts to the context of the operation .

Access levels influence polymorphism by determining which methods can be overridden or overloaded. Private methods are inaccessible outside their defining class and cannot be overridden, thereby not supporting polymorphism in the subclass context. Conversely, final methods cannot be overridden but can still be called, which means they prevent subclasses from altering specific behavior. This restriction ensures that certain method behaviors remain consistent regardless of subclass modifications but limits the polymorphic potential of these methods .

Polymorphism in Java allows performing a single action in various forms and is derived from Greek words meaning 'many forms.' It is implemented in Java primarily through method overloading and method overriding. Method overloading, a type of compile-time polymorphism, occurs when multiple methods in a class share the same name but differ in parameters, enhancing program readability. Method overriding, a form of runtime polymorphism, is when a subclass provides a specific implementation of a method that exists in its parent class, ensuring that behavior can be extended or modified for specific scenarios .

Method overriding is crucial for runtime polymorphism because it allows the dynamic selection of method implementations to be made at runtime based on the object's actual class. This capability enables the implementation of object-oriented design principles like 'programming to an interface,' where the exact method executed isn't determined until runtime. The overridden method in the subclass takes precedence, allowing specific behavior tailoring while maintaining a consistent class interface, which is vital for frameworks and libraries .

The Object class in Java supports polymorphism through methods that are fundamental to all objects, such as equals(), hashCode(), and toString(). These methods can be overridden in any class to provide class-specific functionality, leveraging polymorphism to present class-specific behavior. For instance, equals() can define a complex equivalence logic, hashCode() supports proper functioning in hash-based collections, and toString() can provide meaningful output. These polymorphic methods facilitate a uniform interaction interface while allowing specific customization .

Static methods in Java can exhibit polymorp_hic behavior in the context of overloading, although they do not support true polymorphism through overriding. Since static methods belong to the class rather than an instance, the Java compiler resolves overloaded static methods at compile time by their parameter lists. Polymorphic behavior is exhibited in the sense that the method call adapts to the parameter types, but it doesn't rely on object instances, distinguishing it from runtime polymorphism .

You might also like