Java Unit-3
Java Unit-3
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
system.out.println(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()
{
System.out.println("without any arguments");
}
}
public Static viod first(int a,int b)
{
System.out.println(a+b);
}
public static void main(string args[])
GD BADESAB Page 1
Java material for B.sc
{
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()
{
System.out.println("overriding methods");
}
}
class override extends simple
{
public viod display()
{
super.display();
System.out.println("overriding simple methods");
}
}
class Override
{
public static void main(string args[])
{
override obj=new override();
obj.display();
}
}
GD BADESAB Page 2
Java material for B.sc
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()
{
System.out.println(“square value=” +(x*x));
}
}
Class two extends one
{
Static void calculate()
{
System.out.println(“square root=” +Math.sqrt(x));
}
}
Class poly
{
Public static void main(String args[])
{
GD BADESAB Page 3
Java material for B.sc
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(){System.out.println("running");}
}
GD BADESAB Page 4
Java material for B.sc
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
GD BADESAB Page 5
Java material for B.sc
GD BADESAB Page 6
Java material for B.sc
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()
{
System.out.println(“super class”);
}
}
class Two extends One
{
void show2()
{
System.out.println(“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 java.lang 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 B.sc
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 java.lang.Object 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.
GD BADESAB Page 8
Java material for B.sc
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
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>{
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 B.sc
class TestInterface2
{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
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(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
GD BADESAB Page 10
Java material for B.sc
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:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed 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) java.net: 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
file.This 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)
{
System.out.println(s);
}
}
javac -d directory javafilename
javac -d . Myclass.java
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
GD BADESAB Page 11
Java material for B.sc
import myPackage.MyClass;
GD BADESAB Page 12
Java material for B.sc
Output:
Compile C:\> javac –d.MyDate.java
package mypack.MyDate;
import java.util.*;
public class DateImp1 implements MyDate
{
public void showDate()
{
Date d=new Date();
System.out.println(d);
}
}
importnmypack.DateImp1;
class DateDisplay
{
public static void main(String args[])
{
DateImp1 obj=new DateImp1();
obj.ShowDate();
}
}
Compile: C:\> javac DateDisplay.java
Run:Java DateDisplay
GD BADESAB Page 13
Java material for B.sc
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 dream.tech;
package dream.tech;
public class Sample
{
public void Show()
{
System.out.println("welcome to Dreamtech");
}
}
Compile: javac –d.Sample.java
import dream.tech.Sample;
class Use
{
public static void main(String args[])
{
Sample obj=new Sample();
obj.Show();
}
}
GD BADESAB Page 14