Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

UNIT III

Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object.
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the parent-child relationship.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
The extends keyword indicates that you are making a new class that derives from an existing
class.

Types of Inheritance:
(1) Single:
Single child class inheriting methods and attributes from a single parent class is known as single
inheritance.

The above figure represents that class B extends only a single class which is class A in that class
A is the Parent class and class B is the child class.

public class A {
public void display() {
System.out.println("I am a method from class A");
}
}

class B extends A {
public void print() {
System.out.println("I am a method from class B");
}

public static void main(String[] args) {


B objB = new B();
objB.display();
objB.print();
}
}

OUTPUT:
I am a method from class A
I am a method from class B
(2). Multilevel
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.

class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}

OUTPUT:
Inside display
Inside area
Inside volume

(3). Hierarchical:
In Hierarchical Inheritance, one class serves as a super class (base class) for more than one
subclass. In the below image, class A serves as a base class for the derived classes B and C.
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");
}
}

public class Test {


public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();
}
}

OUTPUT:
Class A
Class B
Class A
Class C

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();
}
}
OUTPUT:
Hello
Welcome

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");
}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

OUTPUT:
Hello
Welcome

Super Keyword:
 The super keyword refers to super class (parent) objects.
 It is used to call super class variables, methods, and to access the super class constructor.
 The most common use of the super keyword is to eliminate the confusion between super
classes and subclasses that have methods with the same name.

1. Use of super with Variables:


This scenario occurs when a derived class and base class has the same data members.

Example
class Vehicle {
int maxSpeed = 120;
}

class Car extends Vehicle {


int maxSpeed = 180;

void display()
{
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}

class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output:
Maximum Speed: 120

2. Use of super with Methods


This is used when we want to call the parent class method. So whenever a parent and child class
have the same-named methods then to resolve ambiguity we use the super keyword.

Example
class Person {
void message()
{
System.out.println("This is person class\n");
}
}
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
void display()
{
message();
super.message();
}
}
class Test {
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}

Output
This is student class
This is person class

3. Use of super with constructors


The super keyword can also be used to access the parent class constructor. One more important
thing is that ‘super’ can call both parametric as well as non-parametric constructors depending on
the situation.

Example
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}

class Student extends Person {


Student()
{
super();
System.out.println("Student class Constructor");
}
}

class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}

Output
Person class Constructor
Student class Constructor

Advantages of Using Java super keyword


 Enables reuse of code
 Supports polymorphism
 Provides access to parent class behavior
 Allows for customization of behavior
 Facilitates abstraction and encapsulation

Method Overriding:
 If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
 If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.

Rules for Java Method Overriding


 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).

class Parent {
void show()
{
System.out.println("Parent's show()"); }
}

class Child extends Parent {


void show()
{
System.out.println("Child's show()");
}
}

class Main
{
public static void main(String[] args)
{
Parent obj2 = new Child();
obj2.show();
}
}

Output
Child's show()

 If the user wants to access the parent class show () they have to use super keyword or
create object for the parent class.

Understanding Dynamic method dispatch:


Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic
method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time.
 When an overridden method is called through a superclass reference, Java determines
which version (superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination is
made at run time.
 At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
 A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.

Therefore, if a superclass contains a method that is overridden by a subclass, then when different
types of objects are referred to through a superclass reference variable, different versions of the
method are executed. Here is an example that illustrates dynamic method dispatch:

class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
void m1()
{
System.out.println("Inside C's m1 method");
}
}

class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A ref;
ref = a;
ref.m1();
ref = b;
ref.m1();
ref = c;
ref.m1();
}
}

Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method

Abstract Keyword:
“abstract” is a non-access modifier in java applicable for classes, and methods but not variables.
It is used to achieve abstraction which is one of the pillars of Object Oriented
Programming(OOP).

Characteristics of Java abstract Keyword


Abstract classes cannot be instantiated
Abstract methods do not have a body
Abstract classes can have both abstract and concrete methods
Abstract classes can have constructors
Abstract classes can contain instance variables
Abstract classes can implement interfaces

The abstract keyword is a powerful tool for defining abstract classes and methods in Java. By
declaring a class or method as abstract, developers can provide a structure for subclassing and
ensure that certain methods are implemented in a consistent way across all subclasses.

abstract class A {
abstract void m1();
void m2()
{
System.out.println("This is a concrete method.");
}
}

class B extends A {
void m1()
{
System.out.println("B's implementation of m1.");
}
}

public class AbstractDemo {


public static void main(String args[])
{
B b = new B();
b.m1();
b.m2();
}
}

OUTPUT:
B's implementation of m1.
This is a concrete method.

Using final with inheritance


 The final keyword is final that is we cannot change.
 We can use final keywords for variables, methods, and class.
 If we use the final keyword for the inheritance that is if we declare any method with
the final keyword in the base class so the implementation of the final method will be the
same as in derived class.
 We can declare the final method in any subclass for which we want that if any other class
extends this subclass.

Case 1: Declare final methods with inheritance


class FinalDemo {
public final void display() {
System.out.println("This is a final method.");
}
}

class Main extends FinalDemo {


public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

The above program will not run and produce an error.

Case 2: Declare final class with inheritance

final class FinalClass {


public void display() {
System.out.println("This is a final method.");
}
}

class Main extends FinalClass {


public void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}

The above program will not run and produce an error.

Packages:
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.

Userdefined Packages:

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

1) 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.

package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}

package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:
Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:
Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

package pack;
public class A{
public void msg(){
System.out.println("Hello");}
}

package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();
obj.msg();
}
}

Output:
Hello
Understanding Access Protection Importing packages:

Interfaces:
An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains
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 the method body.

interface In1 {
final int a = 10;
void display();
}
class TestClass implements In1 {
public void display(){
System.out.println("Geek");
}
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}

Output
Geek
10

Exception Handling:
Exception is an abnormal condition.
An exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Java provides five keywords that are used to handle the exception. The following table describes
each.

Example Program:
public class JavaExceptionExample
{
public static void main(String args[])
{
try
{
int data=100/0;
System.out.println("This line will never be printed”);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("After Catch”);
}
}

OUTPUT:

Exception in thread main java.lang.ArithmeticException:/ by zero


After Catch

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch


block. The error object created in the try block is throwed to the respective catch block and the
error details are printed in the output. Once an error occurs we can’t return back to the rest of the
statements in the try block. The code which is next to the catch block will be executed.

Using multiple catch clauses:


A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

public class MultipleCatchBlock1 {


public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:
Arithmetic Exception occurs
rest of the code

Working with Finally,


Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs or
not. The finally block follows the try-catch block.

public class TestFinallyBlock2{


public static void main(String args[]){
try {
System.out.println("Inside try block");
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

OUTPUT:
Inside try block
Exception handled
java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...

Throw
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.

For example, we can throw ArithmeticException if we divide a number by another number.


Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance

In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

public class TestThrow1 {


public static void validate(int age) {
if(age<18) {
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

throws
if there is a chance of raising an exception then the compiler always warns us about it and
compulsorily we should handle that checked exception, Otherwise, we will get compile time
error saying unreported exception XXX must be caught or declared to be thrown. To prevent this
compile time error we can handle the exception in two ways:
1. By using try catch
2. By using the throws keyword
class ThrowsExecp {

static void fun() throws IllegalAccessException


{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}

public static void main(String args[])


{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}

Output:
Inside fun().
caught in main.

Understanding Built-in Exceptions

Exceptions that are already available in Java libraries are referred to as built-in exception. These
exceptions are able to define the error situation so that we can understand the reason of getting
this error.

class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9;
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}

Output:
Array Index is Out Of Bounds

Creating user defined Exceptions


Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception according to
user needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.

class MyException extends Exception{


String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}

class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Output:
Starting of try block
Catch Block
MyException Occurred: This is My error Message

You might also like