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

Java Unit 2-1

Uploaded by

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

Java Unit 2-1

Uploaded by

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

Java programming

UNIT 2
1. Inheritance and polymorphism
1.1. Inheritance in Java
1.2. Super and sub class
1.3. Overriding
1.4. Object class
1.5. Polymorphism
1.6. Dynamic binding
1.7. Generic programming
1.8. Casting objects
1.9. Instance of operator
1.10. Abstract class
1.11. Interface in Java
1.12. Package in Java
1.13. UTIL package
Java programming

UNIT 01. INHERITANCE AND POLYMORPHISM


2

1.1. Inheritance
The process of deriving the new class from an old class known as
Inheritance.
1. Here the new class is known as sub class
2. And old class is known as super class
Example:

GRANDFATHER

FATHER

SON/DAUGHTER

a. Where Grand-father is the super class


b. And father is the intermediate super class
c. Son or daughter is sub class.

Types of Inheritance
1. Single level Inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance

1. SINGLE LEVEL INHERITANCE

Only one super class is extend with only one sub class known as single
level inheritance.
Example:

B
Java programming

2. MULTI-LEVEL INHERITANCE

One class extending another class as in a hierarchical structure is known


as multi-level inheritance.
Example:

3. HIERARCHICAL INHERITANCE

The number of classes extending from only one super class. That means
one super class and many number of sub classes
Example:

B C D

4. MULTIPLE INHERITANCE

The number of super classes are extend with only one sub class known
as multiple inheritance. But in Java programming does not support
multiple inheritance, so that the problem should be solved by using an
interface
Example:

Interface A Interface C

Class A
Java programming
GENERAL SYNTAX OF SUB CLASS
class<subclass name>extends<super class name>
{
/*sub class & super class members*/
}

GENERAL SYNTAX OF SINGLE LEVEL INHERITANCE

class A
{
----------------
}
class B extends A
{
----------------
----------------
}
Where A is a Super class, B is a Sub class

GENERAL SYNTAX OF MULTI-LEVEL INHERITANCE

class A
{
}
class B extends A
{
}
class C extends B
{
}
Where A is a Super class, B is a Sub class, C is a Sub class

GENERAL SYNTAX OF HIERARCHICAL INHERITANCE


class A
{
}
class B extends A
{
}
Java programming
class C extends A
{
}
class D extends A
{
}
Where A is a super class, B is a sub class, C is a sub class and D is a sub class

Write a program to show the use of single level inheritance


class A
{
int a;
void showA()
{
a=10;
System.out.println("The val of a="+a);
}
}

class B extends A
{
int b,sum;
void showB()
{
b=20;
sum=a+b;
System.out.println("The val of b="+b);
System.out.println("The val of sum="+sum);
}

public static void main(String args[])


{
B x=new B();
x.showA();
x.showB();
}
}
Java programming
Write a program to show the use of multi-level inheritance
class A
{
int a,b;
void showA()
{
a=50;
b=20;
System.out.println("The val of a=" +a);
System.out.println("The val of b=" +b);
}
}

class B extends A
{
int sum;
void showB()
{
sum=a+b;
System.out.println("The val of sum=" +sum);
}
}

class C extends B
{
double avg;
void showC()
{
avg=sum/2;
System.out.println("The val of Avg="+avg);
}

public static void main(String args[])


{
C x=new C();
x.showA();
x.showB();
x.showC();
}
}
Java programming
Write a program to show the use of hierarchical inheritance
class A
{
double a,b;
void showA()
{
a=20;
b=10;
System.out.println(“The val of a=”+a);
System.out.println(“The val of b=”+b);
}
}

class B extends A
{
double sum;
void showB()
{
sum=a+b;
System.out.println(“The val of sum=”+sum);
}
}

class C extends A
{
double sub;
void showC()
{
sub=a-b;
System.out.println(“The val of sub=”+sub);
}
}

class D extends A
{
double mul;
void showD()
{
mul=a*b;
Java programming
System.out.println(“The val of mul=”+mul);
}
}

class E extends A
{
double div;
void showE()
{
div=a/b;
System.out.println(“The val of div=”+div);
}

public static void main(String args[])


{
B m1=new B();
m1.showA();
m1.showB();
C m2=new C();
m2.showA();
m2.showC();
D m3=new D();
m3.showA();
m3.showD();
E m4=new E();
m4.showA();
m4.showE();
}
}
Java programming
1.2. Overriding methods
It is used to declare same method name in both super class and sub class.
This method is known as overriding method.

General Syntax
class X
{
void show()
{
// class X
}
}

class Y extends X
{
void show()
{
//class Y
}
}

Programming Example
class cannon
{
void camera()
{
System.out.println(“This is cannon camera”);
}
}

class Samsung extends cannon


{
void camera()
{
System.out.println(“This is Samsung camera”);
}

public static void main(String args[])


{
Samsung s=new Samsung();
s.camera();
}
}
Java programming
RULES OF OVERRIDING
1. The same method name should be written in both super class and sub class and
also the order of the arguments is also same.
2. The same method name declared both in super class and sub class and also equal
number of arguments and should take same return type.
3. It is used to take some access specifier do not take different access specifier in both
super class and sub class.
4. Suppose protected access specifier used in super class and public in sub class. This
is also overriding method.

We have to check the status of method overriding in super class and sub class:
Super class Sub class Result
void showA() void showA()
{ {
--------- --------- Valid
--------- ---------
} }
int showA() void showA()
{ {
--------- --------- Valid
--------- ---------
} }
int show(int a) void show(int a, int b)
{ {
--------- --------- Invalid
--------- ---------
} }

DIFFERENCE BETWEEN METHOD OVERLOADING AND METHOD OVERRIDING:


METHOD OVERLOADING METHOD OVERRIDING
1. Overloading means the same method 1. The same method declare in
declare two or more number of times different number of classes with help
in same class. of inheritance.
Java programming
2. Different number of arguments are 2. Same number of arguments are
passed. passed.
3. Different number of data types are 3. Same data types can be used.
used.
4. Different return type can be used. 4. Same return type can be used.
5. Inheritance cannot be used. 5. Inheritance can be used.

Super Keyword
Super is a keyword is used to refer the super class object. This keyword
is used for the following:
 To call super class method from the sub class.
 If both sub class and super class contains the same method. That is known as
method overriding.
 If sub class and super class contains the same variable, then we can access the
super class variable using super keyword.
 To call super class constructor from sub class constructor.

Example:-
class Abc
{
void show()
{
System.out.println(“This is super class”);
}
}

class sup extends Abc


{
void show()
{
super.show();
System.out.println(“This is sub class”);
}
public static void main(String args[])
{
Sup s= new Sup();
s.show();
}
}
Java programming
Write a program to show the use of super keyword
class Abc
{
int x=100;
void show()
{
System.out.println("This is super class");
}
}
class Sup extends Abc
{
int x=200;
void show()
{
super.show();
System.out.println("The super class variable val=" +super.x);
System.out.println("This is sub class");
System.out.println("The sub class variable val="+x);
}
public static void main(String args[])
{
Sup s=new Sup();
s.show();
}
}

Write a program to show the use of super keyword using


constructors
class first
{
int x,y;
first()
{
System.out.println("Default Constructor of super class");
}

first(int a, int b)
{
Java programming
x=a;
y=b;
System.out.println("This is super class constructor");
System.out.println("The val of x="+x);
System.out.println("The val of y="+y);
}
}

class second extends first


{
int x,y;
second()
{
super();
System.out.println("Default constructor of sub class");
}
second(int a , int b)
{
super(100,200);
x=a;
y=b;
System.out.println("This is sub class constructor");
System.out.println("The val of x="+x);
System.out.println("The val of y="+y);
}

public static void main(String args[])


{
second s1=new second();
second s2=new second(300,400);
}
}

Rules of Super Keyword


 The super should be the first statement inside the constructor.
 The super and This keyword cannot be used together.
 The super cannot be used inside the static method. If you want to access super
class constructor inside a sub class we should use super() only.
Java programming
DIFFERENCE BETWEEN This AND Super
This KEYWORD Super KEYWORD
1. It refers to current object. 1. It refers to super class
2. It is used to call the constructor 2. It is used to call the constructor of
super class
3. It is used to differentiate between the 3. It is used to differentiate between
instance variable and local variable instance variable of sub class.
of same class

FINAL VARIABLES, METHODS AND CLASSES

Final variables
Final is a keyword it is used to assign the fixed value of execution and it
is like a constant, once we assign the value of variable it cannot be
changed.

The final variables must be declared in the place of local variables, but that
variables cannot be modified.

NOTE
scanner class
Java Scanner class is part of the java.util package. The Scanner is mostly used
to receive user input and parse them into primitive data types such as int, double or
default String. It's a utility class to parse data using regular expressions by generating
tokens. The Scanner class of the java.util package is used to read input data from
different sources like input streams, users, files, etc.

Write a program to show the use of final variables


import java.util.scanner;
class Area
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
double r,area;
Java programming
final double pi=3.142;
System.out.println(“Enter the val of r”);
r=sc.nextDouble();
area=pi*r*r;
System.out.println(“The area of the circle=”+area);
}
}

Final methods
The methods in the class can be declared as final, to prevent sub class
from overriding it and it is unchangeable.
The final methods can be over-ridden and it is completely secured.

Write a program to show the use of final methods


class finemethod
{
final void secure()
{
System.out.println(“This is highly secure”);
}
void nonsecure()
{
System.out.println(“This is non secure superclass”);
}
}
class demo extends finemethod
{
void nonsecure()
{
System.out.println(“This is non secure sub class”);
}
public static void main(String args[])
{
demo d=new demo();
d.secure();
d.nonsecure();
}
}
Java programming
Final class
The keyword final when we declare the beginning of super class the
entire class should not be inherited with sub class.
The final class all the methods are also completely secured cannot be accessed in
a sub class.

Write a program to show the use of final class


final class finmethod
{
void secure1()
{
System.out.println(“This is highly secure1”);
}
void secure2()
{
System.out.println(“This is highly secure2”);
}
public static void main (String args[])
{
finmethod d=new finmethod();
d.secure1();
d.secure2();
}
}

Abstract class and methods


Abstract class
Abstract is a keyword that contains zero or more number of abstract
methods and the class should start from abstract keyword. This is known
as abstract class.
The final class all the methods are also completely secured cannot be accessed in
a sub class.

General Syntax:
abstract class abs
{
Java programming
abstract void run();
abstract void run();
}

Write a program to show the use of abstract class


abstract class abst
{
int a,b,c;
abstract void add();
abstract void sub();
}

class mno extends abst


{
void add()
{
a=10;
b=5;
c=a+b;
System.out.println("The add of a and b="+c);
}

void sub()
{
a=10;
b=5;
c=a-b;
System.out.println("The sub of a and b="+c);
}

public static void main(String args[])


{
mno a=new mno();
a.add();
a.sub();
}
}
Java programming
Abstract methods
Abstract method is a method that should be declared in the abstract class
and it starts from abstract keyword but this method does not have any
body called as an abstract method.

General Syntax:
abstract class abs
{
abstract void run();
abstract void sleep();
}

Here, run() and sleep() are the abstract methods but there is no body in this
class. If we want to extend these methods that should be extended with another
class and do it.

DIFFERENCE BETWEEN class AND abstract class


CLASS ABSTRACT CLASS
1. The class does not contain abstract 1. It contains abstract methods.
method
2. The class can be instantiated. 2. The abstract class cannot be
instantiated.

POLYMORPHISM IN JAVA
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 morphos. The word "poly" means many and "morphos" means
forms. So polymorphism means many forms.

There are two types of polymorphism in Java:


1) Compile-time polymorphism
2) Runtime polymorphism.
Java programming

We can perform polymorphism in java by method overloading & method overriding.


If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.

1. Compile time Polymorphism in Java


Compile time polymorphism or Static Method Dispatch is a process in
which a call to an overloading method is resolved at compile time only.
public class MNO
{
public static void main(String args[])
{
Compile obj = new Compile();
obj.display();
obj.display("Polymorphism");
}
}
class Compile
{
void display()
{
System.out.println("In Display without parameter");
}
void display(String value)
{
System.out.println("In Display with parameter" + value);
}
}

2. Runtime Polymorphism in Java


Runtime Polymorphism or Dynamic Method Dispatch or Late Binding
Polymorphism is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.
Java programming
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting
If the reference variable of parent class refers to the object of child class, it
is known as upcasting.

For example:
class A
{
}
class B extends A
{
}

For upcasting, we can use the reference variable of class type or an interface type.

For Example:
interface XYZ
{
}
class A
{
}
class B extends A implements XYZ
{
}
Java programming
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends
Bike class and overrides its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as


runtime polymorphism.
class Bike
{
void run()
{
System.out.println("running");
}
}
class Splendor extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}
public static void main(String args[])
{
Bike b = new Splendor();//upcasting
b.run();
}
}

Java Runtime Polymorphism


Example: BANK
Consider a scenario where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to banks. For example,
SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.
Java programming
This example is also given in method overriding but there was no upcasting.

class Bank
{
float getRateOfInterest()
{
return 0;
}
}

class SBI extends Bank


{
float getRateOfInterest()
{
return 8.4f;
}
}
class ICICI extends Bank
{
float getRateOfInterest()
{
return 7.3f;
}
}
class AXIS extends Bank
{
float getRateOfInterest()
{
return 9.7f;
}
}
class TestPolymorphism
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest:
"+b.getRateOfInterest());
b=new ICICI();
Java programming
System.out.println("ICICI Rate of Interest:
"+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest:
"+b.getRateOfInterest());
}
}

Java Runtime Polymorphism


Example: Animal
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
}
class Cat extends Animal
{
void eat()
{
System.out.println("eating rat...");
}
}
class Lion extends Animal
{
void eat()
{
System.out.println("eating meat...");
}
Java programming
}
class TestPolymorphism3
{
public static void main(String[] args)
{
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}
}

Java Runtime Polymorphism with Multilevel Inheritance

Let’s see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal
{
void eat()
{
System.out.println("eating");
}
}

class Dog extends Animal


{
void eat()
{
System.out.println("eating fruits");
}
}
class BabyDog extends Dog
{
void eat()
{
System.out.println("drinking milk");
}
Java programming
public static void main(String args[])
{
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}

DIFFERENCE BETWEEN compile time AND run time polymorphism


COMPILE-TIME POLYMORPHISM RUN-TIME POLYMORPHISM
1. Compile time polymorphism means 1. Run time polymorphism where at
binding is occurring at compile time run time we come to know which
method is going to invoke
2. It can be achieved through Static 2. It can be achieved through dynamic
Binding binding
3. Inheritance is not involved 3. Inheritance is involved
4. Method overloading is an example of 4. Method overriding is an example of
compile time polymorphism runtime polymorphism
5. Fast binding 5. Late binding

STATIC BINDING

When type of the object is determined at compiled time (by the


compiler), it is known as static binding. If there is any private,
final or static method in a class, there is static binding.
Example of static binding:
class Dog
{
private void eat()
{
System.out.println("dog is eating...");
}
Java programming
public static void main(String args[])
{
Dog d1=new Dog();
d1.eat();
}
}

DYNAMIC BINDING

When type of the object is determined at run-time, it is known


as dynamic binding.

Example of dynamic binding:


class Animal
{
void eat()
{
System.out.println("animal is eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Animal a=new Dog();
a.eat();
}
}

INTERFACES AND PACKAGES


INTERFACE
It is a collection of public abstract methods and public static final
variables known as an Interface.
Java programming
General syntax:
interface interfacename
{
public abstract method();
public static final variables;
}
Example:

interface Animal
{
public static final age=25;
public abstract eat();
public abstract run();
}

EXTENDING INTERFACES

The extends is a keyword this word is inherit between two or more


number of interfaces
Example:
interface interface1
{
public abstract method1();
}
interface interface2 extends interface1
{
public abstract method2();
}

Multiple inheritance using an interface as shown by the following


interface A
{
public abstract shownA();
}
Java programming
interface B
{
public abstract shownB();
}
interface C
{
public abstract shownC();
}
interface ABC extends A,B,C
{
public abstract shownABC();
}

IMPLEMENTING INTERFACES
General syntax:
class classname implements interfacename
{
//class body
}

Where implements is a keyword, this word is used to inherit between


class and interface known as implementing an interface.

RULES OF INTERFACE:
 The declaration of the interface must be used for interface keyword.
 Interface is a fully unimplemented structure.
 Interface must be used for public static final variables.
 Must be used for public abstract method only.
 Inherit between 2 interfaces must be used for extends keyword.
 Inherit between class and interface must be used for implements.

Write a program to show the use of class implementing an interface


interface Animal
{
public static final int age=25;
public abstract void Tiger();
Java programming
public abstract void Elephant();
}
class Danger implements Animal
{
public void Tiger()
{
System.out.println(“this is tiger”);
System.out.println(“this tiger age is” +age);
}
public void Elephant()
{
System.out.println(“this is elephant”);
System.out.println(“this elephant age is” +age);
}
public static void main(String args[])
{
Danger d=new Danger();
d.Tiger();
d.Elephant();
}
}

Program to show the use of implementing more than one interface

interface BCOM
{
public static final int bno=300;
public void course_BCOM();
}

interface BCA
{
public static final int cno=300;
public void course_BCA();
}

class course implements BCOM,BCA


{
public void course_BCOM()
{
Java programming
System.out.println("----------------BCOM----------------");
System.out.println("This is commerce course");
System.out.println("our college strength="+bno);
}

public void course_BCA()


{
System.out.println("----------------BCA-----------------");
System.out.println("This is computer application course");
System.out.println("our college strength="+cno);
}

public static void main(String args[])


{
course c=new course();
c.course_BCOM();
c.course_BCA();
}
}

Program to show the use of multiple inheritance using an interface

interface A
{
public static final double a=10.25;
public void showA();
}

interface B
{
public static final double b=15.75;
public void showB();
}

interface C
{
public static final double c=20.25;
public void showC();
}

interface ABC extends A,B,C


Java programming
{
public void showABC();
}

class multiple implements ABC


{
double sum, avg;
public void showA()
{
System.out.println("the val of a="+a);
}

public void showB()


{
System.out.println("the val of b="+b);
}

public void showC()


{
System.out.println("the val of c="+c);
}

public void showABC()


{
sum=a+b+c;
avg=sum/3;
System.out.println("sum="+sum);
System.out.println("avg="+avg);
}

public static void main(String args[])


{
multiple m=new multiple();
m.showA();
m.showB();
m.showC();
m.showABC();
}
}
Java programming
Accessing Interface variables
The interface variables are always final static variables so that it must be
assign within an interface body only after that implementing with class and
access it.

Program to show the use of accessing interface variables


interface ABC
{
public static final int x=100;
public static final int y=200;
public static final int z=300;
public void calculate();
}

class calculate implements ABC


{
int large;
public void calculate()
{
large=x;
if(y>large)
large=y;
if(z>large)
large=z;
System.out.println("the val of x="+x);
System.out.println("the val of y="+y);
System.out.println("the val of z="+z);
System.out.println("the largest val ="+large);
}

public static void main(String args[])


{
calculate c=new calculate();
c.calculate();
}
}
Java programming
Various forms of interface implementation
1. Between classes extends keyword.
2. Between interfaces using extends keyword.
3. Between class and interface using implements.

The diagrammatical representation

DIFFERENCE BETWEEN CLASS AND INTERFACE:


CLASS INTERFACE

1. Fully implemented structure 1. Fully unimplemented structure


2. Class can be instantiated 2. Interface cannot be instantiated
3. Contains both static and non-static 3. Contains only final static variables
variables
4. No abstract methods are allowed 4. Allows only abstract methods
Java programming
5. Class declaration using class keyword 5. Interface declaration using interface
keyword
6. Class can extend only one class 6. Interface can extend more than one
interface

DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE:


ABSTRACT CLASS INTERFACE
1. It is partially implemented and 1. Fully unimplemented structure
partially unimplemented structure
2. Contains classeS and abstract 2. Contain only abstract methods
methods
3. Contains instance variables 3. Contains final static variables
4. Can extend only one class 4. Can extend more than one interface
5. It inherit with class using extends 5. It inherit with class using
keyword implements keyword

Access control modifiers


There are 4 types of Access control modifiers:

1. Private: It access only within the class and do not access outside the class.
Example:
class private
{
int a;
private int b;
}

Where b is a private variable we should use within the above class only.

2. Default: It is accessible anywhere in the same package.


Example:
class Def
{
int a, b;
}
Where a and b are default variable can use these variables in the entire package.
Java programming
3. Public: It is accessible anywhere in the same package and anywhere in
outside package & also access everywhere in java program.

Example:
import java.bca;
class public
{
public int a;
}

Where a public variable it can use one class to another class, one package to
another class, one package to another package and everywhere.

4. Protected: It is accessible anywhere in the same package and can access from
super class to sub class means in the concept of inheritance.
Example:
import java.bca;
class port
{
protected int a;
}

Where a & b are public variables can access within the class and from one class
to another class within that particular package.

PACKAGES
It is a collection of related classes.
The package is divided into two types:
1. Java API packages
2. User defined packages

1. Java API packages


The packages are already stored in java compiler and built in classes these
packages are access by import keyword
Java programming
Example:

1. Lang: This is used to support basic language features and handling arrays and
string that package name is java. Lang.
Example: import java. Lang;

2. Util: This package contains utility of various kinds of classes.


Example: scanner input class
That name of the package is java. Util & importing file is import java.
Util;
3. Awt: This package is used for abstract window tool kit and it supports GUI.
Programming package name is java. Awt
4. Sql: This package classes related to database access and the name of package is
javax.sql import javax.sql;
5. I/O: It supports for input/output operations the name of the package is java.io
and the importing file name is import java.io

NETWORKING
java.net supports to develop network program and the importing file is import
java.net;

APPLET
To implement the applet programs and the name of package is java.applet
importing file name is import java.applet.Applet;
Java programming
2. User defined packages
The user can defined his own package known as user defined package. The creation
of user defined package using the following:

General syntax:
package pack_name;

Example:
package pack_1;

Where, pack_1 is the name of the package.

If you create sub packages as show by the following:


Example:
package pack_1.pack_2;

RULES OF PACKAGE:
1. The package declaration must be starts with package word.
2. The name of the package and storage / path of package directory name should be
same.
3. Instead of that directory to set the java path.
4. That particular package class should be compilation only do not run it.
5. Importing the package from one package to another package using import
keyword.
6. Class name should starts with alphabetical letter.

Casting Object
The Casting object is used take from parent class object to child class
object or one interface to another during at compile time.

Type casting of objects in Java


1. Upcasting object
2. Downcasting object

1. Upcasting is casting a subtype to a super type in an upward direction to the


inheritance tree.
Java programming
2. Downcasting refers to the procedure when subclass type refers to the object of
the parent class is known as downcasting.

UPCASTING
Upcasting is a type of object typecasting in which a child object is type
casted to a parent class object.
By using the Upcasting, we can easily access the variables and methods of the
parent class to the child class. Here, we don't access all the variables and the method.
We access only some specified variables and methods of the child class. Upcasting is
also known as Generalization and Widening.

Program to show the use of upcasting


class Parent
{
void PrintData()
{
System.out.println("method of parent class");
}
}
class Child extends Parent
{
void PrintData()
{
System.out.println("method of child class");
}
}
class UpcastingExample
{
public static void main(String args[])
{
Parent obj1 = (Parent) new Child();
Parent obj2 = (Parent) new Child();
obj1.PrintData();obj2.PrintData();
}
}
Java programming
DOWNCASTING
Downcasting is another type of object typecasting. In upcasting, we
assign a parent class reference object to the child class. In Java, we cannot
assign a parent class reference object to the child class, but if we perform
downcasting, we will not get any compile-time error.

Program to show the use of downcasting


class Parent
{
String name;

// A method which prints the data of the parent class

void showMessage()
{

System.out.println("Parent method is called");

}
}

// Child class
class Child extends Parent
{
int age;
// Performing overriding
@Override
void showMessage()
{

System.out.println("Child method is called");

}
}
Java programming
public class Downcasting
{
public static void main(String[] args)
{
Parent p = new Child();
p.name = "Shubham";
// Performing Downcasting Implicitly
//Child c = new Parent(); // it gives compile-time error
// Performing Downcasting Explicitly
Child c = (Child)p;
c.age = 18;
System.out.println(c.name);
System.out.println(c.age);
c.showMessage();
}
}

Instanceof operator
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it


compares the instance with type.
It returns either true or false. If we apply the instanceof operator with any variable
that has null value, it returns false.

Program to show the use of instanceof operator


class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
Java programming
Generic Programming in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
It makes the code stable by detecting the bugs at compile time.

Before generics, we can store any type of objects in the collection, i.e., non-generic.
Now generics force the java programmer to store a specific type of objects.

Advantages of Java Generics


1. Type-safety
2. Type casting is not required
3. Compile-Time Checking

Example:
import java.util.*;
class TestGeneric
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();
list.add("Manoj");
list.add("Dilip");
list.add("Likitha");
list.add("Sunitha");
list.add("Keerthana");
//list.add(32);//compile time error
String s=list.get(1); //type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Java programming
Generic method
Like the generic class, we can create a generic method that can accept any type of
arguments. Here, the scope of arguments is limited to the method where it is declared.
It allows static as well as non-static methods.

Let's see a simple example of java generic method to print array elements. We are
using here E to denote the element.

Program to show the use of generic method


public class TestGenerics
{
public static < E > void printArray(E[] elements)
{
for ( E element : elements)
{
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A',
'T','P','O','I','N','T' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}

You might also like