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
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
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()
{
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[])
{
One o=new two();
o.calculate(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 B.sc
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();
obj.run();
}
}//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(){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();
}
}
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 B.sc
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();
}
}
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.
WideningTypeCastingExample.java
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;
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
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;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("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()
{
System.out.println(“super class”);
}
}
class Two extends One
{
void show2()
{
System.out.println(“sub class”);
}
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.
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 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>{
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 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");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
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 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;
public class PrintName
{
public static void main(String args[])
{
String name = "hello";
MyClass obj = new MyClass();
obj.getNames(name);
}
}
Note : MyClass.java 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 B.sc
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 –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);
}
}
Compile:C:\> javac –d.DateImp1.java
importnmypack.DateImp1;
class DateDisplay
{
public static void main(String args[])
{
DateImp1 obj=new DateImp1();
obj.ShowDate();
}
}
Compile: C:\> javac DateDisplay.java
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 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();
}
}
Compile: javac Use.java
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