Java Unit 2-1
Java Unit 2-1
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
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
Types of Inheritance
1. Single level Inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance
4. Multiple 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
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*/
}
class A
{
----------------
}
class B extends A
{
----------------
----------------
}
Where A is a Super class, B is a Sub class
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
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);
}
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);
}
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);
}
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”);
}
}
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
--------- ---------
} }
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”);
}
}
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);
}
}
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.
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.
General Syntax:
abstract class abs
{
Java programming
abstract void run();
abstract void run();
}
void sub()
{
a=10;
b=5;
c=a-b;
System.out.println("The sub of a and b="+c);
}
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.
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.
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.
class Bank
{
float getRateOfInterest()
{
return 0;
}
}
Let’s see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal
{
void eat()
{
System.out.println("eating");
}
}
STATIC BINDING
DYNAMIC BINDING
interface Animal
{
public static final age=25;
public abstract eat();
public abstract run();
}
EXTENDING INTERFACES
IMPLEMENTING INTERFACES
General syntax:
class classname implements interfacename
{
//class body
}
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.
interface BCOM
{
public static final int bno=300;
public void course_BCOM();
}
interface BCA
{
public static final int cno=300;
public void course_BCA();
}
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();
}
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.
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. Lang: This is used to support basic language features and handling arrays and
string that package name is java. Lang.
Example: import java. Lang;
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;
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.
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.
void showMessage()
{
}
}
// Child class
class Child extends Parent
{
int age;
// Performing overriding
@Override
void showMessage()
{
}
}
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).
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.
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.