Java Unit 3
Java Unit 3
04/16/2024
SYLLABUS
04/16/2024
INHERITANCE IN JAVA
04/16/2024
INHERITANCE IN JAVA
The below flow diagram shows that class B extends only one class which is A.
The subclass constructor uses the keyword super to invoke the constructor method of
superclass.
04/16/2024
class Vehicle
{
Vehicle()
{
System.out.println("Vehicle is created");
}
}
class Bike extends Vehicle{
Bike()
{
super();//
will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();
}
}
04/16/2024
Multiple Inheritance
• Multiple Inheritance” refers to the concept of one class extending (Or inherits) more
than one base class.
• The problem with “multiple inheritance” is that the derived class will have to manage
the dependency on two base classes.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
04/16/2024
Example of method overriding
• In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation.
• The name and parameter of the method are the same, and there is IS-A
relationship between the classes, so there is method overriding.
04/16/2024
//Java Program to demonstrate the real scenario //Test class to create objects and call the
of Java Method Overriding methods
//where three classes are overriding the method class Test2{
of a parent class. public static void main(String args[]){
//Creating a parent class. SBI s=new SBI();
class Bank{ ICICI i=new ICICI();
int getRateOfInterest(){return 0;} AXIS a=new AXIS();
} System.out.println("SBI Rate of Interest:
//Creating child classes. "+s.getRateOfInterest());
class SBI extends Bank{ System.out.println("ICICI Rate of Interest:
int getRateOfInterest(){return 8;} "+i.getRateOfInterest());
} System.out.println("AXIS Rate of Interest:
"+a.getRateOfInterest());
class ICICI extends Bank{ }
int getRateOfInterest(){return 7;} }
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;} Output:
} SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
04/16/2024
Polymorphism in Java
• Polymorphism in Java is a concept by which we can perform a single action in
different ways.
• The word "poly" means many and "morphs" means forms.
• polymorphism means many forms.
• There are two types of polymorphism in Java:
compile-time polymorphism
runtime polymorphism.
• If you overload a static method in Java, it is the example of compile time
polymorphism.
04/16/2024
Runtime Polymorphism in Java
• Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.
• 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.
Upcasting
• If the reference variable of Parent class refers to the object of Child class, it is
known as upcasting.
class A{} interface I{}
class B extends A{} class A{}
A a=new B();//upcasting class B extends A
implements I{}
• For upcasting, we can use the reference variable of class type or an interface type.
04/16/2024
Example of Java Runtime Polymorphism
04/16/2024
Java Runtime Polymorphism with Data Member
• A method is overridden, not the data members, so runtime polymorphism can't be
achieved by data members.
• Rule: Runtime polymorphism can't be achieved by data members.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
04/16/2024
Java Runtime Polymorphism with Multilevel Inheritance
• 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");}
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();
} }
04/16/2024
Static Binding and Dynamic Binding
04/16/2024
Understanding Type
variables have a type Objects have a type
• Each variable has a type, it may be • An object is an instance of particular java
class,but it is also an instance of its
primitive and non-primitive. superclass.
int data=30;
• Here data variable is a type of int. class Animal{}
class Dog{
private void eat(){System.out.println("dog is eating...");
}
04/16/2024
Dynamic binding
• When type of the object is determined at run-time, it is known as dynamic
binding.
class Animal{
void eat(){System.out.println("animal is eating...");}
}
04/16/2024
Generic programming
• Generics mean parameterized types.
• The idea is to allow type (Integer, String, … etc, and user-defined types) to be a
parameter to methods, classes, and interfaces.
• Using Generics, it is possible to create classes that work with different data types.
• An entity such as class, interface, or method that operates on a parameterized type is
called a generic entity.
Why Generics?
• Type-safety: We can hold only a single type of objects in generics. It doesn?t allow
to store other objects.
• Type casting is not required: There is no need to typecast the object.
• Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime. The good programming strategy says it is far better to handle the problem at
compile time than runtime.
ClassOrInterface<Type> ArrayList<String>
Syntax
04/16/2024
to use generic collection
Full Example of Generics in Java
import java.util.*; import java.util.*;
class TestGenerics1{ class TestGenerics1{
public static void main(String args[]){ public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); ArrayList<String> list=new ArrayList<String>();
list.add("rahul"); list.add("rahul");
list.add("jai"); list.add("jai");
//list.add(32);//compile time error //list.add(32);//compile time error
String s=list.get(1);//type casting is not required String s=list.get(1);//type casting is not required
System.out.println("element is: "+s); System.out.println("element is: "+s);
04/16/2024
Example of Java Generics using Map
import java.util.*;
class TestGenerics2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"vijay");
map.put(4,"umesh");
map.put(2,"ankit");
Iterator<Map.Entry<Integer,String>> itr=set.iterator();
while(itr.hasNext()){
Map.Entry e=itr.next();//no need to typecast
System.out.println(e.getKey()+" "+e.getValue());
}
}}
04/16/2024
Java Object Typecasting
• java object typecasting one object reference can be type cast into another object
reference.
• The cast can be to its own class type or to one of its subclass or superclass types
or interfaces.
• There can be 2 casting java scenarios
• Upcasting
• Downcasting
Upcasting
• Upcasting is a type of object typecasting in which a child object is typecasted 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.
04/16/2024
• We access only some specified variables and methods of the child class.
• Upcasting is also known as Generalization and Widening.
class Parent{
void PrintData() {
System.out.println("method of parent class");
}
}
04/16/2024
//Parent class public class Downcasting{
class Parent {
String name; public static void main(String[] args)
// A method which prints the data of the parent class {
void showMessage() Parent p = new Child();
{ p.name = "Shubham";
System.out.println("Parent method is called"); // Performing Downcasting Implicitly
} //Child c = new Parent(); // it gives compile-
} time error
// Child class
class Child extends Parent { // Performing Downcasting Explicitly
int age; Child c = (Child)p;
@Override c.age = 18;
void showMessage() System.out.println(c.name);
{ System.out.println(c.age);
System.out.println("Child method is called"); c.showMessage();
} }
} }
04/16/2024
Why we need Upcasting and Downcasting?
In Java, we rarely use Upcasting. We use it when we need to develop a code that
deals with only the parent class.
• Downcasting is used when we need to develop a code that accesses behaviors of
the child class.
04/16/2024
Difference between Upcasting and Downcasting
S.No Upcasting Downcasting
1. A child object is typecasted to a parent The reference of the parent class object is passed to
object. the child class.
3. In the child class, we can access the The methods and variables of both the classes(parent
methods and variables of the parent and child) can be accessed.
class.
4. We can access some specified methods All the methods and variables of both classes can be
of the child class. accessed by performing downcasting.
04/16/2024
Java instanceof
• 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.
Simple example of java instanceof
class Simple1{ class Animal{}
public static void main(String args[]){ class Dog1 extends Animal{//Dog inherits
Simple1 s=new Simple1(); Animal
System.out.println(s instanceof public static void main(String args[]){
Simple1);//true Dog1 d=new Dog1();
} System.out.println(d instanceof Animal);//true
} }
04/16/2024
}
Instanceof in java with a variable that have null value
• If we apply instanceof operator with a variable that have null value, it returns
false.
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof
Dog2);//false
}
}
04/16/2024
Possibility of downcasting with instanceof
class Animal { }
04/16/2024
Downcasting without the use of java instanceof
class Animal { }
class Dog4 extends Animal {
static void method(Animal a) {
Dog4 d=(Dog4)a;//downcasting
System.out.println("ok downcasting performed");
}
public static void main (String [] args) {
Animal a=new Dog4();
Dog4.method(a);
}
}
04/16/2024
interface Printable{}
class A implements Printable{
public void a(){System.out.println("a method");}
}
class B implements Printable{
public void b(){System.out.println("b method");}
}
class Call{
void invoke(Printable p){//upcasting
if(p instanceof A){
A a=(A)p;//Downcasting
a.a();
}
if(p instanceof B){
B b=(B)p;//Downcasting
b.b();
} } }//end of Call class
class Test4{
public static void main(String args[]){
Printable p=new B();
Call c=new Call();
c.invoke(p);
04/16/2024 }}
Abstract class in Java
• A class which is declared with the abstract keyword is known as an abstract
class in Java
• Before learning the Java abstract class, let's understand the abstraction in Java
first.
• 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.
04/16/2024
Example of abstract class
abstract class A{}
04/16/2024
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e.
unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided
through method, e.g., getShape() method
s.draw();
}
}
04/16/2024
Abstract class having constructor, data member and methods
• An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");} }
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
04/16/2024}
Interface in Java
• An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
• The interface in Java is a mechanism to achieve abstraction.
• There can be only abstract methods in the Java interface, not method body.
• It is used to achieve abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and
variables.
• It cannot have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.
04/16/2024
Why use Java interface?
• There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
Syntax:
interface <interface_name>{
04/16/2024
Java Interface Example: Drawable
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided
by method e.g. getDrawable()
d.draw();
}}
04/16/2024
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as 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();
}
}
04/16/2024
Interface inheritance
• A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
04/16/2024
Java 8 Default Method in Interface
• Since Java 8, we can have method body in interface. But we need to make it
default method.
interface Drawable{
void draw();
default void msg()
{System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw()
{System.out.println("drawing
rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
04/16/2024
Java 8 Static Method in Interface
• Since Java 8, we can have static method in interface.
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw()
{System.out.println("drawing
rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
04/16/2024
Nested Interface in Java
• An interface can have another interface which is known as a nested interface.
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
04/16/2024
4) Abstract class can provide the Interface can't provide the implementation of abstract class.
implementation of interface.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract class can extend another An interface can extend another Java interface only.
Java class and implement multiple Java
interfaces.
An abstract class can be extended using An interface can be implemented using keyword "implements".
keyword "extends".
8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
04/16/2024
Java 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.
Advantage of Java Package
• Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
• Java package provides access protection.
• Java package removes naming collision.
04/16/2024
Simple example of java package
Example
javac -d . Simple.java
04/16/2024
How to access package from another package?
• There are three ways to access the package from outside the package.
• import package.*;
• import package.classname;
• fully qualified name.
Using packagename.*
• If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
• The import keyword is used to make the classes and interface of another package
accessible to the current package. /save by B.java
//save by A.java package mypack;
package pack; import pack.*;
public class A{ class B{
public void msg() public static void main(String args[]){
{System.out.println("Hello");} A obj = new A();
} obj.msg();
04/16/2024 } }
Using packagename.classname
//save by A.java //save by B.java
package mypack;
package pack; import pack.A;
public class A{
public void msg() class B{
{System.out.println("Hello");} public static void main(String args[]){
} A obj = new A();
obj.msg();
} }
04/16/2024
• AbstractSequentialList: This class provides a skeletal implementation of the List interface to
minimize the effort required to implement this interface backed by a “sequential access” data store
(such as a linked list).
• AbstractSet: This class provides a skeletal implementation of the Set interface to minimize the effort
required to implement this interface.
• ArrayDeque: Resizable-array implementation of the Deque interface.
• ArrayList: Resizable-array implementation of the List interface.
• Arrays: This class contains various methods for manipulating arrays (such as sorting and searching).
• BitSet: This class implements a vector of bits that grows as needed.
• Calendar: The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next
week.
• Collections: This class consists exclusively of static methods that operate on or return collections.
• Currency: Represents a currency.
04/16/2024
• Date: The class Date represents a specific instant in time, with
millisecond precision.
• Dictionary<K,V>: The Dictionary class is the abstract parent of any class,
such as Hashtable, which maps keys to values.
• EnumMap,V>: A specialized Map
• EnumSet: A specialized Set implementation for use with enum types.
• EventListenerProxy: An abstract wrapper class for an EventListener class
which associates a set of additional parameters with the listener.
• EventObject: The root class from which all event state objects shall be
derived.
• FormattableFlags: FomattableFlags are passed to the
Formattable.formatTo() method and modify the output format for
Formattables.
04/16/2024
• Formatter: An interpreter for printf-style format strings.
• GregorianCalendar: GregorianCalendar is a concrete subclass of Calendar and
provides the standard calendar system used by most of the world.
• HashMap<K,V>: Hash table based implementation of the Map interface.
• HashSet: This class implements the Set interface, backed by a hash table (actually
a HashMap instance).
• Hashtable<K,V>: This class implements a hash table, which maps keys to values.
• IdentityHashMap<K,V>: This class implements the Map interface with a hash
table, using reference-equality in place of object-equality when comparing keys
(and values).
• Objects: This class consists of static utility methods for operating on objects.
• Observable: This class represents an observable object, or “data” in the model-
view paradigm.
04/16/2024
• LinkedHashMap<K,V>: Hash table and linked list implementation of the Map
interface, with predictable iteration order.
• LinkedHashSet: Hash table and linked list implementation of the Set interface,
with predictable iteration order.
• LinkedList: Doubly-linked list implementation of the List and Deque interfaces.
• ListResourceBundle: ListResourceBundle is an abstract subclass of
ResourceBundle that manages resources for a locale in a convenient and easy to
use list.
• Locale – Set 1, Set 2: A Locale object represents a specific geographical, political,
or cultural region.
• Locale.Builder: Builder is used to build instances of Locale from values
configured by the setters.
• PriorityQueue: An unbounded priority queue based on a priority heap.
04/16/2024
• Properties: The Properties class represents a persistent set of properties.
• PropertyPermission: This class is for property permissions.
• PropertyResourceBundle: PropertyResourceBundle is a concrete subclass of
ResourceBundle that manages resources for a locale using a set of static strings
from a property file.
• Random: An instance of this class is used to generate a stream of pseudorandom
numbers
• ResourceBundle: Resource bundles contain locale-specific objects.
• ResourceBundle.Control: ResourceBundle.Control defines a set of callback
methods that are invoked by the ResourceBundle.getBundle factory methods
during the bundle loading process.
• Scanner: A simple text scanner which can parse primitive types and strings using
regular expressions.
04/16/2024
NPTEL LINK
https://www.youtube.com/watch?v=hBh_CC5y8-s
https://www.youtube.com/watch?v=8cm1x4bC610&t=11s
Innovative content of oops concepts
https://www.youtube.com/watch?v=LPT6m33Y6is
https://www.youtube.com/watch?v=7GwptabrYyk
04/16/2024
References
1. Herbert Schildt, Java The Complete Reference, 7 /9th Edition, Tata McGraw Hill, 2007.
2. https://www.geeksforgeeks.org
3. www.slideshare.net
4. https://www.javatpoint.com/
5. https://www.w3schools.com/java/
6. https://www.edureka.co
7. https://www.softwaretestinghelp.com
04/16/2024