Unit-2
Inheritance
Inheritance is a capability of one class to inherit the properties of another class.
That means a properties of superclass(parentclass) will be inherited by the
sublass(childclass).
Super Class: The superclass represents the class whose features are inherited by a
sub-class.
class AddSub{ public static void main(String args[])
{
int num1=300,num2=150;
AddSub as=new AddSub();
void add()
as.add();
{ }
int a=num1+num2; }
System.out.println(“Sum=“+a);
}
Sub Class: Also known as a derived or extended class, this class inherits the features from another class.
Also along with the inherited fields and methods, the class generated from the class can add fields and
methods of its own. class MulDiv extends AddSub
{
void mul()
class AddSub{
int num1=300,num2=150;
{
void add()
int c=num1*num2;
{ System.out.println(“Multiply=“+c);
int a=num1+num2; }
System.out.println(“Sum=“+a);
void div()
{
}
int d=num1/num2;
Void sub() System.out.println(“Division=“+d);
{ }
int b=num1-num2;
System.out.println(“diff=“+b); }
class MathOperation{
} public static void main(String args[])
} {
MulDiv m=new MulDiv();
Write a program to perform mathematical operations. m.add();
Create a class called AddSub with methods to add and subtract.
Create another class called MulDiv that extends from AddSub class to use
m.sub();
the member data of the super class. MulDiv should have methods to multiply m.mul();
and divide
m.div();}}
Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is
common to all subclasses. Child classes can directly use the
parent class code.
• Method Overriding: Method Overriding is achievable only
through Inheritance.
• Abstraction: The concept of abstract where we do not have
to provide all details, is achieved through inheritance.
Abstraction only shows the functionality to the user.
There are 5 Types of Inheritance
Single Inheritance
Only one class is derived from the parent class. In this type of
inheritance, the properties are derived from a single parent class and
not more than that.
Multilevel Inheritance
In multilevel Inheritance a parent class becomes the child class of
another class.
In the following diagram: class B is a parent class of C, however it is also
a child class of A. In this type of inheritance, there is a concept of
intermediate class, here class B is an intermediate class.
Hybrid Inheritance
Hybrid Inheritance is a Combination of more than one types of
inheritance in a single program. For example class B & C extends A and
another class D extends class C then this is a hybrid inheritance example
because it is a combination of single and hierarchical inheritance.
Hierarchical Inheritance
In Hierarchical Inheritance more than one class extends the same class.
As shown in the following diagram, classes B, C & D extends the same
class A.
Multiple Inheritance
Multiple Inheritance is the concept of one class extending more than
one classes, which means a child class has more than one parent
classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritance.
Method overriding
If subclass (child class) has the same method as declared in the superclass( parent class), it is known
as method overriding .
class Vehicle{
//this is parent class
void run()
{System.out.println("Vehicle is running");}
}
//This is child class
class Bike extends Vehicle{
void run()
{System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike obj = new Bike();//creating object ClassName object = new ClassName();
obj.run();//calling method object.method();
}
}
Object class in java
The Object class resides within the java.lang package.
It serves as a foundation for all classes, directly or indirectly.
If a class doesn't extend any other class, it's a direct child of Object.
If it extends another class, it's indirectly derived.
Object Class Methods:
1.toString()
The toString() method in Java is a String representation of an object, converting it into a human-readable
format.
class Student {
int id = 101;
String name = "Rahul";
public String toString() {
return "Student[id=" + id + ", name=" + name + "]";
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.toString()); // Output: Student[id=101, name=Rahul]
}
}
2.hashCode()
A hash code is an integer value that gets generated by the hashing algorithm. Hash
code is associated with each object in Java and is a distinct value. It converts an
object's internal address to an integer through an algorithm. It is not the memory
address, it is the integer representation of the memory address.
String s = "Test";
System.out.println(s.hashCode()); // Output: e.g., 2603186
3. equals () Method
This method compares two objects and returns whether they are equal or not.
String a = "Java";
String b = new String("Java");
System.out.println(a.equals(b)); // Output: true
4.finalize()
Just before Java's garbage collector reclaims an object, the finalize() method is
invoked.
class FinalizeExample {
protected void finalize() {
System.out.println("Object is being garbage collected");
}
public static void main(String[] args) {
FinalizeExample obj = new FinalizeExample();
obj = null;
System.gc(); // Suggests JVM to run GC
}
}
5.notify()
Awakens a single thread waiting on this object. (a thread represents sequential flow of execution within a
program)
class Shared {
synchronized void testWait() {
try {
System.out.println("Thread is waiting...");
wait();
System.out.println("Thread resumed.");
} catch (InterruptedException e) {
System.out.println(e);
}
}
synchronized void testNotify() {
System.out.println("Notifying...");
notify(); // or notifyAll();
}
}
6.clone() Method
The clone() method is used to create an exact copy of this object. It makes a new
object and copies all the data of the this object to the new object.
7. notifyAll()
Awakens all threads waiting on this object.
8.wait()
causes the current thread to wait for the specified milliseconds,
until another thread notifies (invokes notify() or notifyAll()
method).
9.getclass()
returns the Class object of this object.
String s = "Hello";
System.out.println(s.getClass()); // Output: class java.lang.String
Polymorphism
Poly means many and morphism means forms.
Polymorphism is considered one of the important features of Object-
Oriented Programming. Polymorphism allows us to perform a single
action in different ways.
Compile time(a program is converted to the
machine code) polymorphism
It is also known as (Static Binding / Early Binding). This type of
polymorphism is achieved by function overloading or operator
overloading.
Subtypes of compile time polymorphism:
1. Method Overloading:
It means multiple functions can have the same name but
with different parameter lists.
2. Operator Overloading
where the operators such as +, -, *, etc. can be given additional meanings
when applied to user-defined data types.
//method overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class Test {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(5, 10)); // calls int version
System.out.println(c.add(5.5, 2.3)); // calls double version
}
}
Operator Overloading (Not Supported in Java)
• Java does not support operator overloading (unlike C++).
• The only exception is the + operator, which is overloaded for String concatenation.
System.out.println("Hello " + "World"); // "Hello World"
Run time(it is the period of time when a
program is running) polymorphism
It is also known as Dynamic binding /late binding. It is a process in
which a function call to the overridden method is resolved at Runtime.
This type of polymorphism is achieved by Method Overriding.
Virtual functions
• A virtual function is a function that is declared in a base (parent)
class and overridden in a derived (child) class, with the decision of
which version of the function to run made at runtime (known as
dynamic dispatch or runtime polymorphism).
class Animal {
void makeSound() {
System.out.println("Some animal sound");
}
}
class Dog extends Animal {
@Override
void makeSound() { •Even though a is declared as Animal, the method from Dog is
System.out.println("Bark"); executed.
•This is because makeSound() is a virtual function in Java.
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // reference is Animal, object is Dog
a.makeSound(); // Output: Bark (Dog's version is called)
}
}
Binding
Connecting a method call to the method body is known as
binding.
There are two types of binding
1.Static Binding (also known as Early Binding)
2.Dynamic Binding (also known as Late Binding).
Static Binding (also known as Early Binding):If there is any private, final or static method
in a class, there is static binding.
Class Vehicle{
private void run(){
System.out.println(“vehicle is running");
}
public static void main(String args[])
{
Vehicle v1=new Vehicle();
v1.run();
}
}
Dynamic Binding (also known as Late Binding).
When type of the object is determined at run-time, it is known as dynamic binding
class Vehicle{
void run()
{
System.out.println(“Vehicle is running");
}
}
class Bike extends Vehicle{
void run()
{
System.out.println(“bike is running");
}
public static void main(String args[]){
Bike b=new Bike();
b.run();
}
} o/p:bike is running
Generic Programming
Generics was first introduced in Java 1.5. Now it is one of the
most profound features of java programming language.
-> Generic programming enables the programmer to create
classes, interfaces and methods in which type of data is
specified as a parameter.
-> Generics provide type safety. Type safety means ensuring
that an operation is being performed on the right type of
data.
Generic class
Generic class is a class which can hold any kind of objects, to create
Generic class we have to specify generic type after the class name.
Syntax:
Generic interfaces
We can also create a generic interface by specifying the <T> after
the interface name.
syntax:
In the above program, we first passed an Integer type parameter to the Generic class. Then, we
passed a String type parameter to the same Generic class. Hence, we reused the same class for two
different data types. Thus, Generics helps in code reusability
Casting Objects
Typecasting is the assessment of the value of one primitive data type
to another type. In java, there are two types of casting namely
upcasting and downcasting .
1.Upcasting is casting a subtype to a super type in an upward direction to
the inheritance tree.
● Implicit casting means class typecasting done by the compiler without
cast syntax.
● Explicit casting means class typecasting done by the programmer with
cast syntax.
import java.io.*; // Main class
class GFG
// Parent class
{
class Parent
{
void show() public static void main(String[] args)
{ {
// Creating a Parent class object
System.out.println("Parent show method is called"); // but referencing it to a Child class
} Parent obj = new Child();
} obj.show();
}
}
// Child class
class Child extends Parent o/p : Child show method will be called
{
void show()
{
System.out.println("Child show method is called");
}
Here parent class object is called but referred to the child’s class object.
2.Downcasting
Example of Down Casting
class One{ public class Test{
void m1() public static void main(String args[])
{ {
System.out.println(“m1 method in class Two obj2=(Two) new One();
One”); obj2.m1();
} obj2.m2();
} }
class Two extends One{ }
void m2(){
System.out.println(“m2 method in class
Two”); o/p: it shows exception i.e classCastException
}
}
Instance of operator
The instanceof operator in Java is used to test whether an object is an instance of a
specific class or implements a particular interface. It provides a way to check the
type of an object at runtime, and it is commonly used in type checking and type
casting.
Syntax
The syntax for the instanceof operator is:
object instanceof ClassName
object is the instance you want to test.
ClassName is the class or interface you want to check against.
How It Works
● Returns true if the object is an instance of the specified class or interface, or if it is an
instance of a subclass or class that implements the specified interface.
● Returns false otherwise.
public class Animal { }
public class Dog extends Animal { }
public class Cat extends Animal { }
public class TestInstanceOf {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
System.out.println(myDog instanceof Dog); // true
System.out.println(myDog instanceof Animal); // true
System.out.println(myCat instanceof Dog); // false
System.out.println(myCat instanceof Animal); // true
System.out.println(myDog instanceof Cat); // false
}}
Abstract class and method:
Java abstract class is a class that can not be instantiated by itself, it needs to be
subclassed by another class to use its properties. An abstract class is declared using
the "abstract" keyword in its class definition.we can override the methods by using
the abstract keyword in the method definition.
ex:
Syntax: abstract class Bike{
abstract class classname abstract void run();
{ }
abstract void methodname( ); class Honda4 extends Bike{
} void run()
{System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
} }
Interface in java
Multiple Inheritance is the concept of one class extending more than
one classes, which means a child class has more than one parent
classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritance.
Java provides an alternative approach known as interfaces to
support the concept of multiple inheritance.
Although java class cannot be a subclass of more than one
superclass ,it can implement more than one interface.
Defining Interface:
An interface is basically a kind of class.Like classes interfaces
contain methods and variables but with a major difference.The
difference is that interface do not specify any code to implement
these methods ,and data fields contain only constants.
The general form/syntax of interface is:
interface interfacename
{
variable declaration;
methods declaration;
}
Variables are declared as :
syntax: static final type variablename=value;
ex: static final int i=100; // all variables are declared as constants
Methods are declared as:
Method declaration will contain only a list of methods without any body
statements.
syntax: returntype methodname (parameterlist);
ex: void display();
Example of interface with two variables and one method &
one variable and two methods:
example1: example2:
interface hello interface hello
{ {
static final int i=0; static final int i=0;
static final String name=”vandana’; float show(float x,float y);
void display(); void display();
} }
Extending Interfaces:
interface name2 extends name1
{
body of name 2
}
ex:
interface ItemConstants
{
int i=0;
string name=”vandana”; //here all the variables are declared like normal variables but in interface everything is
considered as constant
}
interface Item extends ItemConstants
{
void show();
}
Implementing Interfaces:
Step 1: Define the interfaces Step 3: Create an object of the class and call the interface
interface Interface1 { methods
void method1(); MyClass obj = new MyClass();
} obj.method1();
obj.method2();
interface Interface2 {
void method2();
}
Step 2: Implement the interfaces in the class
public class MyClass implements Interface1, Interface2 {
public void method1() {
// implementation of method1
}
public void method2() {
// implementation of method2
}
}
// Declare the interfaces
interface ComputerScience {
void program();
}
interface Mathematics{
void practice();
}
// Implement the interfaces in a class
class Duck implements ComputerScience, Mathematics{
public void program()
{
System.out.println("We are
programming");
}
public void practice()
{
System.out.println("We are practicing");
}
}
// Use the class to call the methods from the interfaces
class Main {
public static void main(String[] args)
{
Duck duck = new Duck();
duck.program();
duck.practice();
}
Package in java
In small projects, all the java files have unique names. So, it is not
difficult to put them in a single folder.
But, in the case of huge projects where the number of java files is large,
it is very difficult to put files in a single folder because the manner of
storing files would be disorganized..
Moreover, if different java files in various modules of the project have
the same name, it is not possible to store two java files with the same
name in the same folder because it may occur naming conflict.
This problem of naming conflict can be overcome by using the concept
of packages. A package is nothing but group of related classes,
interfaces, and sub-packages according to their functionality.
There are two different types of packages in Java. They are:
1. Predefined Packages in Java (Built-in Packages)
2. User-defined Package
Built in package and User defined package
Built-in packages are existing java packages that come along with the
JDK. For example, java.lang, java.util, java.io, etc.
The package which is defined by the user is called a User-defined package. It
is used to create user-defined classes and interfaces
To create class inside package
//sytax:package packagename;
package FirstPackage;
class Welcome {
public static void main(String[] args)
{
System.out.println( "This Is my First Package Program");
}
}
Example of package is:
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Util package
One of the most important Java packages is the java.util package. The java.util package contains several pre-written
classes that can act as a base to solve commonly occurring problems in software development.
To load the basic utility classes and interfaces provided by the java.util package, we need to use Java's import
keyword. The import keyword is used to access and load the package and its respective classes into the Java
program.
Example 1: To Load the Whole Util Package
import java.util.*;
this statement will load all the pre-written classes and interfaces provided by the java.util package.
Example 2: To Load a Specific Class from the java.util Package
import java.util.Scanner;
The above statement is importing the Scanner class available in the java.util package. This class is widely used to take
input from the user in a Java program.
Class Description
Scanner Text scanner used to take user inputs
Arrays Provides methods for array manipulation
LinkedList Implements Doubly-linked list data structure
HashMap Implements Map data structure using Hash
tables
Stack Implements last-in-first-out (LIFO) data
structure
Date Represents a specific instance of time
Calendar Provides methods to manipulate calendar
fields