Unit 3
Unit 3
Unit 3
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");
}
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");
}
}
OUTPUT:
Class A
Class B
Class A
Class C
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();
}
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.
Example
class Vehicle {
int maxSpeed = 120;
}
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
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
Example
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor
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.
class Parent {
void show()
{
System.out.println("Parent'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.
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).
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.");
}
}
OUTPUT:
B's implementation of m1.
This is a concrete method.
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
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:
Output:
Arithmetic Exception occurs
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.
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.
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 {
Output:
Inside fun().
caught in main.
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
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