Java_Unit 2
Java_Unit 2
Inheritance in Java
Java, Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the mechanism in Java
by which one class is allowed to inherit the features (fields and methods) of another class. In Java,
Inheritance means creating new classes based on existing ones. A class that inherits from another class can
reuse the methods and fields of that class. In addition, you can add new fields and methods to your current
class as well.
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. It is one of the ways
by which Java achieves Run Time Polymorphism.
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.
Important Terminologies Used in Java Inheritance
Class: Class is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base
class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in addition to
the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Example
In the below example of inheritance, class Employee is a base class, class Engineer is a derived class that
extends the Employee class and class Test is a driver class to run the program.
// Java Program to illustrate Inheritance (concise)
import java.io.*;
// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary + "\nBenefits : " + E1.benefits);
}
}
Output
Salary : 60000
Benefits : 10000
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’
inherits all the properties of the class ‘A’.
Example
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}
// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output
Geeks
for
Geeks
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as
well as the derived class also acts as the base class for other classes. In the below
image, class A serves as a base class for the derived class B, which in turn serves as
a base class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.
Example
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.util.*;
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
// Calling method from class One
g.print_geek();
Example
// Java program to illustrate the
// concept of Hierarchical inheritance
class A {
public void print_A() { System.out.println("Class A"); }
}
class B extends A {
public void print_B() { System.out.println("Class B"); }
}
class C extends A {
public void print_C() { System.out.println("Class C"); }
}
class D extends A {
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
Example
// Java program to illustrate the
// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
interface One {
public void print_geek();
}
interface Two {
public void print_for();
}
// Drived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output
Geeks
for
Geeks
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple
inheritance is also not possible with classes. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require
the use of Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel
Inheritance and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance with classes.
Therefore, it is indeed possible to implement Hybrid inheritance using classes alone, without relying on
multiple inheritance type.
within package. It cannot be accessed from outside the package. It provides more accessibility than
In this example, we have created two packages pack and mypack. We are accessing the A class from outside
its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
Methods, variables, and constructors that are declared private can only be accessed within the declared
class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class, if public getter methods are present in
the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from the
outside world.
In this example, we will create two classes A and B within the same package p1. We will declare a method
in class A as private and try to access this method from class B and see the result.
// Class A
class A {
private void display() {
System.out.println("GeeksforGeeks");
}
}
// Class B
class B {
public static void main(String args[]) {
A obj = new A();
The protected access modifier is specified using the keyword protected. The methods or data members
declared as protected are accessible within the same package or subclasses in different packages.
In this example, we will create two packages, p1 and p2. Class A in p1 has a protected method display. Class
B in p2 extends A and accesses the protected method through inheritance by creating an object of class B.
// protected modifier
package p2;
// Class B is subclass of A
class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.display();
}
}
Explanation: The above example demonstrates that a protected method is accessible in a subclass from a
different package using inheritance.
import p1.*;
class B {
public static void main(String args[]) {
// static variable
static int b = 20;
void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;
System.out.println(a);
// referring current class(i.e, class RR)
// static variable(i.e, b)
this.b = 600;
System.out.println(b);
}
public static void main(String[] args)
{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().GFG();
}
}
Output
100
600
super keyword
1. super is a reserved keyword in java i.e, we can’t use it as an identifier.
2. super is used to refer super-class’s instance as well as static members.
3. super is also used to invoke super-class’s method or constructor.
4. super keyword in java programming language refers to the superclass of the class where the super
keyword is currently being used.
5. The most common use of super keyword is that it eliminates the confusion between the super
classes and subclasses that have methods with same name.
super can be used in various contexts as given below:
it can be used to refer immediate parent class instance variable
it can be used to refer immediate parent class method
it can be used to refer immediate parent class constructor.
Example
// Program to illustrate super keyword
// refers super-class instance
class Parent {
// instance variable
int a = 10;
// static variable
static int b = 20;
}
this Super
The current instance of the class is represented The current instance of the parent class is
by this keyword. represented by the super keyword.
In order to call the default constructor of the In order to call the default constructor of the
current class, we can use this keyword. parent class, we can use the super keyword.
It can be referred to from a static context. It It can be referred to from a static context. It
means it can be invoked from the static context. means it can be invoked from the static context.
We can use it to access only the current class We can use it to access the data members and
data members and member functions. member functions of the parent class.
Output:
Arguments: 1
Arguments: 1 and 4
2. Changing Data Types of the Arguments
In many cases, methods can be considered Overloaded if they have the same name but have different
parameter types, methods are considered to be overloaded.
// Java Program to Illustrate Method Overloading
// By Changing Data Types of the Parameters
// Importing required classes
import java.io.*;
// Class 1
// Helper class
class Product {
// Multiplying three integer values
public int Prod(int a, int b, int c)
{
int prod1 = a * b * c;
return prod1;
}
// Multiplying three double values.
public double Prod(double a, double b, double c)
{
double prod2 = a * b * c;
return prod2;
}
}
class GFG {
public static void main(String[] args)
{
Product obj = new Product();
// Class 1
// Helper class
class Student {
// Method 1
public void StudentId(String name, int roll_no)
{
System.out.println("Name :" + name + " "
+ "Roll-No :" + roll_no);
}
// Method 2
public void StudentId(int roll_no, String name)
{
// Again printing name and id of person
System.out.println("Roll-No :" + roll_no + " "
+ "Name :" + name);
}
}
// Class 2
// Main class
class GFG {
// Main function
public static void main(String[] args)
{
// Creating object of above class
Student obj = new Student();
Example
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}
}
Output :
Time is 8 am
Turning on SmartPhone...
Note: The data members can’t achieve the run time polymorphism.
Output:
Value of PI: 3.14159
Uses of Packages
1. Organizing Code: Packages help group similar functionality into modules. For example, all database-
related classes can go into a `com.example.database` package.
2. Avoiding Naming Conflicts: In large projects, it’s possible to have classes with the same names. Packages
provide namespaces, so two classes with the same name can exist in different packages.
3. Access Control: Java packages provide access control mechanisms. Classes, methods, and fields can have
package-level visibility.
4. Reusability: Code can be organized into packages that can be reused across projects.
Importing Packages
Java provides the `import` statement to import classes or entire packages.
1. Importing a Single Class:
import com.example.HelloWorld;
2. Importing All Classes in a Package:
import com.example.*;
In the second example, all classes within the `com.example` package will be imported.
Sub-packages in Java
Java supports sub-packages, which are simply packages within other packages. There is no special syntax for
sub-packages; they are treated like regular packages, but the hierarchy is created by adding dots in the
package name.
Example:
package com.example.utils;
The `utils` package is a sub-package of `com.example`.
You can nest packages as deeply as required:
package com.example.database.connection;
This would represent a `connection` package under `database` under `com.example`.
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.
o Java Interface also represents the IS-A relationship.
o It cannot be instantiated just like the abstract class.
o Since Java 8, we can have default and static methods in an interface.
o Since Java 9, we can have private methods in an interface.
Syntax:
interface <interface_name>{
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
If age was 20, you would not get an exception:
Example
checkAge(20);
The output will be:
Access granted - You are old enough!
The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang
is implicitly imported into all Java programs, most exceptions derived from RuntimeException are
automatically available.
Types of Java Built-in Exceptions
Built-in Exceptions in Java are categorized into two categories Checked Exceptions and Unchecked
Exceptions.
Checked Exceptions: The checked exceptions are handled by the programmer during writing the code, they
can be handled using the try-catch block. These exceptions are checked at compile-time.
Unchecked Exceptions: The unchecked exceptions are not handled by the programmer. These exceptions
are thrown on run-time. Some of the unchecked exceptions are NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException, etc.
1 ArithmeticException
Arithmetic error, such as divide-by-zero.
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String[] args) {
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
} catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output
Can't divide a number by 0
8 IllegalThreadStateException -Requested operation not compatible with the current thread state.
CloneNotSupportedException - Attempt to clone an object that does not implement the Cloneable
17
interface.
class VoterList{
int age;
VoterList(int age){
this.age = age;
}
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {