Programming in Java-Unit III
Programming in Java-Unit III
Single inheritance
Java
// Java program to illustrate the
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class
class one {
System.out.println("Green");
// Driver class
// Main function
g.print_for();
}
Output
Green
for
Green
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.
Multilevel Inheritance
Java
// Java program to illustrate the
import java.io.*;
import java.lang.*;
import java.util.*;
class one {
System.out.println("Green");
System.out.println("Green ");
}
// Drived class
g.print_ green();
g.print_for();
g.print_ green();
Output
Green
for
Green
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one subclass. In the below image, class A serves as a base class for the derived classes
B, C, and D.
Java
// Java program to illustrate the
class A {
class B extends A {
class C extends A {
class D extends A {
public void print_D() { System.out.println("Class D"); }
// Driver Class
public class Test {
obj_B.print_A();
obj_B.print_B();
obj_C.print_A();
obj_C.print_C();
obj_D.print_A();
obj_D.print_D();
Output
Class A
Class B
Class A
Class C
Class A
Class D
Java support Multiple Inheritance (Through
Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A and B.
Multiple Inheritance
Java
// Java program to illustrate the
import java.io.*;
import java.lang.*;
import java.util.*;
interface one {
interface two {
public void print_for();
System.out.println("Green");
// Drived class
c.print_green();
c.print_for();
c.print_green();
}
}
Output
Green
for
Green
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent class
objects. An understanding of Inheritance and Polymorphism is needed in order to
understand the Java super keyword. The keyword “super” came into the picture with
the concept of Inheritance.
Characteristics of super Keyword in Java
In Java, the super keyword is used to refer to the parent class of a subclass. Here are
some of its characteristics:
super is used to call a superclass constructor: When a subclass is created, its
constructor must call the constructor of its parent class. This is done using the
super() keyword, which calls the constructor of the parent class.
super is used to call a superclass method: A subclass can call a method defined in
its parent class using the super keyword. This is useful when the subclass wants
to invoke the parent class’s implementation of the method in addition to its own.
super is used to access a superclass field: A subclass can access a field defined in
its parent class using the super keyword. This is useful when the subclass wants
to reference the parent class’s version of a field.
super must be the first statement in a constructor: When calling a superclass
constructor, the super() statement must be the first statement in the constructor of
the subclass.
super cannot be used in a static context: The super keyword cannot be used in a
static context, such as in a static method or a static variable initializer.
super is not required to call a superclass method: While it is possible to use the
super keyword to call a method in the parent class, it is not required. If a method
is not overridden in the subclass, then calling it without the super keyword will
invoke the parent class’s implementation.
Overall, the super keyword is a powerful tool for subclassing in Java, allowing
subclasses to inherit and build upon the functionality of their parent classes.
class Vehicle {
int maxSpeed = 120;
void display()
// Driver Program
class Test {
small.display();
Output
Maximum Speed: 120
Method Overriding
Inheritance is an OOP property that allows us to derive a new class (subclass) from
an existing class (superclass). The subclass inherits the attributes and methods of
the superclass.
Now, if the same method is defined in both the superclass and the subclass, then
the method of the subclass class overrides the method of the superclass. This is
known as method overriding.
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code
Output:
I am a dog.
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
Output
Animals can move
Dogs can walk and run
In the above example, you can see that even though b is a type of Animal it runs the move method
in the Dog class. The reason for this is: In compile time, the check is made on the reference type.
However, in the runtime, JVM figures out the object type and would run the method that belongs
to that particular object.
Therefore, in the above example, the program will compile properly since Animal class has the
method move. Then, at the runtime, it runs the method specific for that object.
abstract keyword in java
In Java, 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). Following are different contexts where abstract can be
used in Java.
Characteristics of Java abstract Keyword
In Java, the abstract keyword is used to define abstract classes and methods. Here are
some of its key characteristics:
Abstract classes cannot be instantiated: An abstract class is a class that cannot
be instantiated directly. Instead, it is meant to be extended by other classes, which
can provide concrete implementations of its abstract methods.
Abstract methods do not have a body: An abstract method is a method that does
not have an implementation. It is declared using the abstract keyword and ends
with a semicolon instead of a method body. Subclasses of an abstract class must
provide a concrete implementation of all abstract methods defined in the parent
class.
Abstract classes can have both abstract and concrete methods: Abstract classes
can contain both abstract and concrete methods. Concrete methods are
implemented in the abstract class itself and can be used by both the abstract class
and its subclasses.
Abstract classes can have constructors: Abstract classes can have constructors,
which are used to initialize instance variables and perform other initialization
tasks. However, because abstract classes cannot be instantiated directly, their
constructors are typically called constructors in concrete subclasses.
Abstract classes can contain instance variables: Abstract classes can contain
instance variables, which can be used by both the abstract class and its subclasses.
Subclasses can access these variables directly, just like any other instance
variables.
Abstract classes can implement interfaces: Abstract classes can implement
interfaces, which define a set of methods that must be implemented by any class
that implements the interface. In this case, the abstract class must provide concrete
implementations of all methods defined in the interface.
Overall, 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.
// Parent Class
// Child Class
void printInfo()
System.out.println(name);
System.out.println(age);
System.out.println(salary);
// driver Class
class base {
// main function
// object created
Output
aakanksha
21
55552.2
o The package makes the search easier for the classes and interfaces.
o It provides a fully qualified name that avoids naming conflicts.
o It also controls access.
o It organizes classes in a folder structure.
o It improves code reusability.
o Programmer can group classes and interfaces into a related package.
Creating a Package
To create a package, follow the steps given below:
Suppose, a programmer creates a class with the name Rectangle in the package shape. The
class with the same name is already present in java.awt package. The compiler allows both
classes if they belong to the different packages. The fully qualified name of each class contains
the package name that differentiate both Rectangle classes. Therefore, the package name of the
user-defined class will be shape.Rectangle and the package name of the predefined class will
be java.awt.Rectangle.
o Package name must be in lower case that avoids conflict with the name of classes and
interfaces.
o Organizations used their internet domain name to define their package names. For
example, com.javatpoint.mypackage. Sometimes, the organization also uses the
region after the company name to name the package. For
example, com.javatpoint.region.mypackage.
o We use underscore in the package name if the domain name contains hyphen or other
special characters or package names begin with a digit or reserved keyword.
Hyphenated-name.example.org org.example.hyphenated_name
Example.int int_.example
123name.example.com com.example._123name
The three main access modifiers private, public and protected provides a range of ways to
access required by these categories.
Simply remember,
private cannot be seen outside of its class, public can be access from anywhere, and protected
can be accessible in subclass only in the hierarchy.
A class can have only two access modifier, one is default and another is public. If the class
has default access then it can only be accessed within the same package by any other code.
But if the class has public access then it can be access from any where by any other code.
Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
Output
Importing a Package
If we want to use a package in Java program it is necessary to import that package at the top of
the program by using the import keyword before the package name.
Syntax:
import packageName;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Display message
// Enter Your Name And Press Enter
System.out.println("Enter Your Name:");
Output
Here In The Above Program, ‘java.util’ package is imported and run for a simple
program. These are called as Inbuilt Packages.
Now in order to create a package in java follow the certain steps as described
below:
1. First We Should Choose A Name For The Package We Are Going To
Create And Include. The package command In The first line in the java
program source code.
2. Further inclusion of classes, interfaces, annotation types, etc that is
required in the package can be made in the package. For example, the
below single statement creates a package name called “FirstPackage”.
Syntax: To declare the name of the package to be created. The package statement
simply defines in which package the classes defined belong.
package FirstPackage ;
Implementation: To Create a Class Inside A Package
1. First Declare The Package Name As The First Statement Of Our Program.
2. Then We Can Include A Class As A Part Of The Package.
Example
// Name of package to be created
package FirstPackage;
So, Inorder to generate the above-desired output first do use the commands as
specified use the following specified commands
Procedure:
1. To generate the output from the above program
Command: javac Welcome.java
2. The Above Command Will Give Us Welcome.class File.
Command: javac -d . Welcome.java
3. So This Command Will Create a New Folder Called FirstPackage.
Command: java FirstPackage.Welcome
Output: The Above Will Give The Final Output Of The Example Program
This Is The First Program for package
Java - Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of
abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.
Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types. Method bodies exist only for default
methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes
and behaviors of an object. And an interface contains behaviors that a class
implements.
Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
Defining Interfaces
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface −
Example
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface. If a class does
not perform all the behaviors of the interface, the class must declare itself as
abstract.
Example
/* File name : MammalInt.java */
public class MammalInt implements Animal {
Extending Interfaces
An interface can extend another interface in the same way that a class can extend
another class. The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
Example
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a
class that implements Hockey needs to implement all six methods. Similarly, a
class that implements Football needs to define the three methods from Football and
the two methods from Sports.
Java Exceptions
In Java, Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the program’s
instructions. Exceptions can be caught and handled by the program. When an
exception occurs within a method, it creates an object. This object is called the
exception object. It contains information about the exception, such as the name and
description of the exception and the state of the program when the exception occurred.
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out-of-disk memory)
Code errors
Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library incompatibility,
infinite recursion, etc. Errors are usually beyond the control of the programmer, and
we should not try to handle errors
Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of
important built-in exceptions in Java.
1. ArithmeticException: It is thrown when an exceptional condition has
occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array
has been accessed with an illegal index. The index is either negative or
greater than or equal to the size of the array.
3. ClassNotFoundException: This Exception is raised when we try to access
a class whose definition is not found
4. FileNotFoundException: This Exception is raised when a file is not
accessible or does not open.
5. IOException: It is thrown when an input-output operation failed or
interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or
doing some processing, and it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the
field (or variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that is
not found.
9. NullPointerException: This exception is raised when referring to the
members of a null object. Null represents nothing
10. NumberFormatException: This exception is raised when a method could
not convert a string into a numeric format.
11. RuntimeException: This represents an exception that occurs during
runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class methods
to indicate that an index is either negative or greater than the size of the
string
13. IllegalArgumentException : This exception will throw the error or error
statement when the method receives an argument which is not accurately fit
to the given relation or condition. It comes under the unchecked exception.
14. IllegalStateException : This exception will throw an error or error message
when the method is not accessed for the particular operation in the
application. It comes under the unchecked exception.
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, the user can also create exceptions which are called ‘user-
defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
The user should create an exception class as a subclass of the Exception
class. Since all the exceptions are subclasses of the Exception class, the
user should also make his class a subclass of it. This is done as:
class MyException extends Exception
We can write a default constructor in his own exception class.
MyException(){}
We can also create a parameterized constructor with a string as a
parameter.
We can use this to store exception details. We can call the
superclass(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
To raise an exception of a user-defined type, we need to create an object to
his exception class and throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
The following program illustrates how to create your own exception class
MyException.
Details of account numbers, customer names, and balance amounts are
taken in the form of three arrays.
In main() method, the details are displayed using a for-loop. At this time, a
check is done if in any account the balance amount is less than the
minimum balance amount to be apt in the account.
If it is so, then MyException is raised and a message is displayed “Balance
amount is less”.
try...catch
The try-catch block is used to handle exceptions in Java. Here's the syntax
of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by a catch block.
When an exception occurs, it is caught by the catch block. The catch block cannot be
used without the try block.
Example: Exception handling using try...catch
class Main {
public static void main(String[] args) {
try {
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Run Code
Output
In the example, we are trying to divide a number by 0. Here, this code generates an
exception.
To handle the exception, we have put the code, 5/0 inside the try block. Now when
an exception occurs, the rest of the code inside the try block is skipped.
The catch block catches the exception and statements inside the catch block is
executed.
If none of the statements in the try block generates an exception, the catch block is
skipped.
Multiple Catch Clauses
Starting from Java 7.0, it is possible for a single catch block to catch multiple
exceptions by separating each with | (pipe symbol) in the catch block.
Catching multiple exceptions in a single catch block reduces code duplication and
increases efficiency. The bytecode generated while compiling this program will be
smaller than the program having multiple catch blocks as there is no code
redundancy.
Note: If a catch block handles multiple exceptions, the catch parameter is implicitly
final. This means we cannot assign any values to catch parameters.
Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}
// multicatch feature
import java.util.Scanner;
try
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
Input 1:
catchblock
Output 1:
Exception encountered java.lang.NumberFormatException:
Either the program terminates abruptly if an exception is not handled or the control is passed
to the exception handler.
In such a situation, there arises a need to include a code that is to be executed irrespective of
whether an exception occurs or not. This means we will execute a piece of code even when
an exception occurs and also when the exception does not occur.
But as try block exits after the exception is raised we cannot put this code in the try block.
Similarly, the catch block has an exception handler, so we cannot put this in the catch block
too.
Thus we need a separate block that contains a code that executes irrespective of whether an
exception occurs or not. Java provides a “finally” block that contains this piece of code.
Hence a finally block in Java can contain critical statements that are to be executed in the
program. The execution of these statements should be carried out even when an exception
occurs or not.
Therefore, we will put code like closing connections, stream objects, etc. or any cleanup code
in the finally block so that they can be executed even if an exception occurs.
The finally block in Java is usually put after a try or catch block. Note that the finally block
cannot exist without a try block. When the finally block is included with try-catch, it becomes
a “try-catch-finally” block.
We can skip the finally block in the exception handling code. This means that finally block is
optional.
If the try block does not raise any exception then the finally block will be executed after the
try block. If there is an exception in the try block then control will pass to the catch block first
and then the finally block.
An exception occurring in finally block behaves in the same way as any other exception.
Even if the try block contains a return statement or branching statements like break and
continue, then the finally block will still be executed.
Keeping these points in mind, let’s go ahead with the general syntax and examples of finally
block.
</em><em> }catch {
</em><em> }finally {
</em><em> }
Though finally block is always executed, there are certain situations or cases in which it
doesn’t execute.
The above program shows a try-catch-finally block. In the try block, a valid operation is
performed and hence no exception is thrown. Therefore, the control is not passed to catch
from try but to finally block.
The following program is another example of try-catch-finally block but in this case, the
exception is thrown in the try block as we perform a divide by zero operation. Thus the
finally block is executed after the try the catch block is executed.
class Main {
public static void main(String args[]) {
//try block
try{
System.out.println("::Try block::");
int num=67/0;
System.out.println(num);
}
//catch block
catch(ArithmeticException e){
System.out.println("::Catch block::");
System.out.println("ArithmeticException::Number divided by zero");
}
//finally block
finally{
System.out.println("::Finally block::");
}
System.out.println("Rest of the code continues...");
}
}
Output
In the above program, we use a method to validate age. If the age is < 18, then an exception is
thrown to indicate the age is not valid.
Throws Clause
We have seen try block to declare exceptions. It contains the code that may raise exceptions.
There is another way to declare an exception and it is using the “throws” keyword.
The declaration of exception using the “throws” keyword tells the programmer that there may
be an exception specified after the “throws” keyword and the programmer should provide
corresponding handler code for this exception to maintain the normal flow of the program.
However, the question arises as to why we need a “throws” keyword when we have a more
reliable try-catch block to declare and handle exceptions.
One reason is as the number of exceptions that might possibly occur increases, the number of
catch block that handles exceptions also increases as one catch block can handle only one
exception.
Similarly, if there are many methods in a program and each method has numerous exceptions
then the code will become unnecessarily long and unmanageable.
Thus declaring an exception with the throws keyword in the method signature and then
handling the method call using try-catch seems to be a viable solution.
Another advantage of declaring exceptions using the throws keyword is that we are forced to
handle the exceptions. If we do not provide a handler for a declared exception then the
program will raise an error.
//method code
}
Let us now implement a Java program to demonstrate the “throws” keyword.
In this program, we have a class Example_throw in which we have a method testMethod. In
the signature of this testMethod, we declare two exceptions IOException and Arithmetic
Exception using the throws keyword. Then in the main function, the exceptions thrown are
handled by the catch block.
import java.io.*;
class Example_Throw {
//declare exception using throws in the method signature
void testMethod(int num) throws IOException, ArithmeticException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ArithmeticException("ArithmeticException");
}
}class Main{
public static void main(String args[]){
try{
//this try block calls the above method so handle the exception
Example_Throw obj=new Example_Throw();
obj.testMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output
// ArithmeticException
class ArithmeticException_Demo {
try {
int a = 30, b = 0;
catch (ArithmeticException e) {
}
Output:
Can't divide a number by 0
dig deeper and look at how user-defined exceptions are created in Java, its
Syntax:
Below is the code which will help to Create a User-defined exception class,
class SampleException{
public static void main(String args[]){
try{
throw new UserException(<value>); // used to create new exception and throw
}
catch(Exception e){
System.out.println(e);
}
}
}
class UserException extends Exception{
// code for exception class
}
lang.Exception.