0% found this document useful (0 votes)
12 views31 pages

Java Super Keyword and Abstraction Guide

The document explains key concepts of Java inheritance, abstract classes, interfaces, packages, access modifiers, and arrays. It covers the use of the 'super' keyword in method overriding and constructor calls, the definition and implementation of abstract classes and methods, and the structure and usage of interfaces. Additionally, it discusses the organization of code using packages, the significance of access modifiers, and the declaration and initialization of arrays in Java.

Uploaded by

principooja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views31 pages

Java Super Keyword and Abstraction Guide

The document explains key concepts of Java inheritance, abstract classes, interfaces, packages, access modifiers, and arrays. It covers the use of the 'super' keyword in method overriding and constructor calls, the definition and implementation of abstract classes and methods, and the structure and usage of interfaces. Additionally, it discusses the organization of code using packages, the significance of access modifiers, and the declaration and initialization of arrays in Java.

Uploaded by

principooja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

super Keyword in Java Inheritance

In method overriding, the same method in the subclass overrides the method in superclass.

In such a situation, the super keyword is used to call the method of the parent class from the
method of the child class.

class Animal {
// method in the superclass
public void eat() {
[Link]("I can eat");
}
}

// Dog inherits Animal


class Dog extends Animal {
// overriding the eat() method
@Override
public void eat() {
// call method of superclass
[Link]();
[Link]("I eat dog food");
}

// new method in subclass


public void bark() {
[Link]("I can bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// call the eat() method


[Link]();
[Link]();
}
}
OUTPUT:
I can eat
I eat dog food
I can Bark
Here, the super keyword is used to call the eat() method present in the superclass.

We can also use the super keyword to call the constructor of the superclass from the constructor
of the subclass.

Java Abstract Class and Abstract Methods


Java Abstract Class

The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes).
We use the abstract keyword to declare an abstract class. For example,

An abstract class can have both the regular methods and abstract methods. For example,

abstract class Language {

// abstract method
abstract void method1();

// regular method
void method2() {
[Link]("This is regular method");
}
}

Java Abstract Method

A method that doesn't have its body is known as an abstract method. We use the
same abstract keyword to create abstract methods. For example,

abstract void display();

Here, display() is an abstract method. The body of display() is replaced by ;.


If a class contains an abstract method, then the class should be declared abstract. Otherwise, it
will generate an error. For example,

Example: Java Abstract Class and Method

Though abstract classes cannot be instantiated, we can create subclasses from it. We can then
access members of the abstract class using the object of the subclass. For example,

abstract class Language {

// method of abstract class


public void display() {
[Link]("This is Java Programming");
}
}

class Main extends Language {

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// access method of abstract class


// using object of Main class
[Link]();
}
}

Output

This is Java programming

Implementing Abstract Methods

If the abstract class includes any abstract method, then all the child classes inherited from the
abstract superclass must provide the implementation of the abstract method. For example,
abstract class Animal {
abstract void makeSound();

public void eat() {


[Link]("I can eat.");
}
}

class Dog extends Animal {

// provide implementation of abstract method


public void makeSound() {
[Link]("Bark bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of Dog class


Dog d1 = new Dog();

[Link]();
[Link]();
}
}

Output

Bark bark
I can eat.

Accesses Constructor of Abstract Classes

An abstract class can have constructors like the regular class. And, we can access the constructor
of an abstract class from the subclass using the super keyword. For example,
abstract class Animal {
Animal() {
….
}
}

class Dog extends Animal {


Dog() {
super();
...
}
}

Here, we have used the super() inside the constructor of Dog to access the constructor of
the Animal.

Note that the super should always be the first statement of the subclass constructor.

Java Abstraction
The major use of abstract classes and methods is to achieve abstraction in Java.

Abstraction is an important concept of object-oriented programming that allows us to hide


unnecessary details and only show the needed information.

This allows us to manage complexity by omitting or hiding details with a simpler, higher-level
idea.

abstract class MotorBike {


abstract void brake();
}

class SportsBike extends MotorBike {

// implementation of abstract method


public void brake() {
[Link]("SportsBike Brake");
}
}
class MountainBike extends MotorBike {

// implementation of abstract method


public void brake() {
[Link]("MountainBike Brake");
}
}

class Main {
public static void main(String[] args) {
MountainBike m1 = new MountainBike();
[Link]();
SportsBike s1 = new SportsBike();
[Link]();
}
}

Output:

MountainBike Brake
SportsBike Brake

Key Points to Remember

 We use the abstract keyword to create abstract classes and methods.

 An abstract method doesn't have any implementation (method body).

 A class containing abstract methods should also be abstract.

 We cannot create objects of an abstract class.

 To implement features of an abstract class, we inherit subclasses from it and create


objects of the subclass.

 A subclass must override all abstract methods of an abstract class. However, if the
subclass is declared abstract, it's not mandatory to override abstract methods.
 We can access the static attributes and methods of an abstract class using the reference of
the abstract class. For example,

[Link]();

Java Interface
An interface is a fully abstract class. It includes a group of abstract methods (methods without a
body).

We use the interface keyword to create an interface in Java. For example,

interface Language {
public void getType();

public void getVersion();


}

Here,

 Language is an interface.

 It includes abstract methods: getType() and getVersion().

Implementing an Interface

Like abstract classes, we cannot create objects of interfaces.

To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.

Example 1: Java Interface

interface Polygon {
void getArea(int length, int breadth);
}
// implement the Polygon interface
class Rectangle implements Polygon {

// implementation of abstract method


public void getArea(int length, int breadth) {
[Link]("The area of the rectangle is " + (length *
breadth));
}
}

class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
[Link](5, 6);
}
}

Output

The area of the rectangle is 30

In the above example, we have created an interface named Polygon. The interface contains an
abstract method getArea().

Here, the Rectangle class implements Polygon. And, provides the implementation of
the getArea() method.

Implementing Multiple Interfaces

In Java, a class can also implement multiple interfaces. For example,

interface A {
// members of A
}

interface B {
// members of B
}
class C implements A, B {
// abstract members of A
// abstract members of B
}

Extending an Interface

Similar to classes, interfaces can extend other interfaces. The extends keyword is used for
extending interfaces. For example,

interface Line {
// members of Line interface
}

// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}

Extending Multiple Interfaces

An interface can extend multiple interfaces. For example,

interface A {
...
}
interface B {
...
}

interface C extends A, B {
...
}
Note: All the methods inside an interface are implicitly public and all fields are implicitly public
static final. For example,

Java Package
A package is simply a container that groups related types (Java classes, interfaces, enumerations,
and annotations).

These packages help you to reserve the class namespace and create a maintainable code.

For example, you can find two Date classes in Java. However, the rule of thumb in Java
programming is that only one unique class name is allowed in a Java project.

How did they manage to include two classes with the same name Date in JDK?

This was possible because these two Date classes belong to two different packages:

 [Link] - this is a normal Date class that can be used anywhere.

 [Link] - this is a SQL Date used for the SQL query and such.

Based on whether the package is defined by the user or not, packages are divided into two
categories:

 Built-in Package
 User-defined Package

Built-in Package

Built-in packages are existing java packages that come along with the JDK. For
example, [Link], [Link], [Link], etc. For example:

import [Link];

class ArrayListUtilization {
public static void main(String[] args) {

ArrayList<Integer> myList = new ArrayList<>(3);


[Link](3);
[Link](2);
[Link](1);

[Link](myList);
}
}

Output:

myList = [3, 2, 1]

User-defined Package

Java also allows you to create packages as per your need. These packages are called user-defined
packages.

How to define a Java package?

To define a package in Java, you use the keyword package.

package packageName;

Java uses file system directories to store packages. Let's create a Java file inside another
directory.

For example:

└── com
└── test

└── [Link]

Now, edit [Link] file, and at the beginning of the file, write the package statement as:

package [Link];

Here, any class that is declared within the test directory belongs to the [Link] package.

Here's the code:

package [Link];

class Test {

public static void main(String[] args){

[Link]("Hello World!");

Output:

Hello World!

Here, the Test class now belongs to the [Link] package.

Package Naming convention

The package name must be unique (like a domain name). Hence, there's a convention to create a
package as a domain name, but in reverse order. For example, [Link]

Here, each level of the package is a directory in your file system. Like this:
└── com
└── company
└── name

How to import packages in Java?

Java has an import statement that allows you to import an entire package (as in earlier examples),
or use only certain classes and interfaces defined in the package.

The general form of import statement is:

import [Link]; // To import a certain class only


import [Link].* // To import the whole package

For example,

import [Link]; // imports only Date class


import [Link].*; // imports everything inside [Link] package

The import statement is optional in Java.

If you want to use class/interface from a certain package, you can also use its fully qualified
name, which includes its full package hierarchy.

Here is an example to import a package using the import statement.

import [Link];

class MyClass implements Date {


// body
}
Access Modifiers
In Java, access modifiers are used to set the accessibility (visibility)
of classes, interfaces, variables, methods, constructors, data members, and the setter methods.
For example,

class Animal {
public void method1() {...}

private void method2() {...}


}

In the above example, we have declared 2 methods: method1() and method2(). Here,
 method1 is public - This means it can be accessed by other classes.
 method2 is private - This means it can not be accessed by other classes.
Note the keyword public and private. These are access modifiers in Java. They are also known as
visibility modifiers.

Types of Access Modifier


There are four access modifiers keywords in Java and they are:

Modifier Description

Default declarations are visible only within the package (package private)

Private declarations are visible within the class only

Protected declarations are visible within the package or all subclasses

Public declarations are visible everywhere

Default Access Modifier


If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by
default the default access modifier is considered. For example

package defaultPackage;
class Logger {
void message(){
[Link]("This is a message");
}
}

Here, the Logger class has the default access modifier. And the class is visible to all the classes
that belong to the defaultPackage package. However, if we try to use the Logger class in another
class outside of defaultPackage, we will get a compilation error.

Private Access Modifier


When variables and methods are declared private, they cannot be accessed outside of the class.
For example,

class Data {
// private variable
private String name;
}

public class Main {


public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


[Link] = "Programiz";
}
}

In the above example, we have declared a private variable named name. When we run the
program, we will get the following error:

[Link]: error: name has private access in Data


[Link] = "Programiz";

The error is generated because we are trying to access the private variable of the Data class from
the Main class.

You might be wondering what if we need to access those private variables. In this case, we can
use the getters and setters method. For example,
class Data {
private String name;

// getter method
public String getName() {
return [Link];
}
// setter method
public void setName(String name) {
[Link]= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();

// access the private variable using the getter and setter


[Link]("Programiz");
[Link]([Link]());
}
}
Output:

The name is Programiz

In the above example, we have a private variable named name. In order to access the variable
from the outer class, we have used methods: getName() and setName(). These methods are called
getter and setter in Java.

Here, we have used the setter method (setName()) to assign value to the variable and the getter
method (getName()) to access the variable.

We have used this keyword inside the setName() to refer to the variable of the class

Protected Access Modifier


When methods and data members are declared protected, we can access them within the same
package as well as from subclasses. For example,

class Animal {
// protected method
protected void display() {
[Link]("I am an animal");
}
}

class Dog extends Animal {


public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
[Link]();
}
}
Output:

I am an animal

Public Access Modifier


When methods, variables, classes, and so on are declared public, then we can access them from
anywhere. The public access modifier has no scope restriction. For example,

// [Link] file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
[Link]("I am an animal.");
[Link]("I have " + legCount + " legs.");
}
}

// [Link]
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


[Link] = 4;
// accessing the public method
[Link]();
}
}

Output:

I am an animal.
I have 4 legs.

Here,

 The public class Animal is accessed from the Main class.

 The public variable legCount is accessed from the Main class.

 The public method display() is accessed from the Main class.


Java Arrays
An array is a collection of similar types of data.

For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names

String[] array = new String[100];

Here, the above array cannot store more than 100 names. The number of values in a Java array is
always fixed.
How to declare an array in Java?

dataType[] arrayName;

 dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects

 arrayName - it is an identifier

For example,

double[] data;

Here, data is an array that can hold values of type double.

To define the number of elements that an array can hold, we have to allocate memory for the
array in Java. For example,

// declare an array
double[] data;

// allocate memory
data = new double[10];

Here, the array can store 10 elements. We can also say that the size or length of the array is 10.

In Java, we can declare and allocate the memory of an array in one single statement. For
example,

double[] data = new double[10];

How to Initialize Arrays in Java?

In Java, we can initialize arrays during declaration. For example,


//declare and initialize and array
int[] age = {12, 4, 5, 2, 5};

How to Access Elements of an Array in Java?

// access array elements


array[index]

Example: Access Array Elements

class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5};

// loop through the array


// using for loop
[Link]("Using for Loop:");
for(int i = 0; i < [Link]; i++) {
[Link](age[i]);
}
}
}

Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare
multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a multidimensional array
is an array itself. For example,
int[][] a = new int[3][4];

How to initialize a 2d array in Java?

Here is how we can initialize a 2-dimensional array in Java.

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
class MultidimensionalArray {
public static void main(String[] args) {

int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};

for (int i = 0; i < [Link]; ++i) {


for(int j = 0; j < a[i].length; ++j) {
[Link](a[i][j]);
}
}
}
}
Exceptional Handling
 The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.

 In Java, an exception is an event that disrupts the normal flow of the program.

 It is an object which is thrown at runtime.

 Exception Handling is a mechanism to handle runtime errors such a


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

 The core advantage of exception handling is to maintain the normal flow of the
application.

 An exception normally disrupts the normal flow of the application that is why we use
exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception
handling in Java.

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered
as the unchecked exception. According to Oracle, there are three types of exceptions:

 Checked Exception

 Unchecked Exception
 Error

1) Checked Exception

 The classes which directly inherit Throwable class except RuntimeException and Error
are known as checked exceptions.

 E.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

 The classes which inherit RuntimeException are known as unchecked exceptions.

 E.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.


Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

 Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

 try : The try keyword is used to specify a block where we should place exception code.
The try block must be followed by either catch or finally. It means, we can't use try block
alone.

 catch : The catch block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

 finally : The finally block is used to execute the important code of the program. It is
executed whether an exception is handled or not.

 throw : The throw keyword is used to throw an exception.

 throws : The throws keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is always used
with method signature.

Here's a list of different approaches to handle exceptions in Java

 try...catch block

 finally block

 throw and throws keyword


Java 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 {

// code that generate exception


int divideByZero = 5 / 0;
[Link]("Rest of code in try block");
}

catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}
}
}
OUTPUT:

ArithmeticException => / by zero

 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 are executed.
 If none of the statements in the try block generates an exception, the catch block is
skipped.

Java finally block

In Java, the finally block is always executed no matter whether there is an exception or not.

The finally block is optional. And, for each try block, there can be only one finally block.

The basic syntax of finally block is:

try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}

If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is
executed after the try block. For each try block, there can be only one finally block.

Example: Java Exception Handling using finally block

class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}

finally {
[Link]("This is the finally block");
}
}
}
Output

ArithmeticException => / by zero


This is the finally block

In the above example, we are dividing a number by 0 inside the try block. Here, this code
generates an ArithmeticException.

The exception is caught by the catch block. And, then the finally block is executed.

3. Java throw and throws keyword

The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to
the catch block.

Example: Exception handling using Java throw

class Main {
public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {


divideByZero();
}
}

Output

Exception in thread "main" [Link]: Trying to


divide by 0
at [Link]([Link])
at [Link]([Link])
In the above example, we are explicitly throwing the ArithmeticException using
the throw keyword.

Similarly, the throws keyword is used to declare the type of exceptions that might occur within
the method. It is used in the method declaration.

Example: Java throws keyword

import [Link].*;

class Main {
// declareing the type of exception
public static void findFile() throws IOException {

// code that may generate IOException


File newFile = new File("[Link]");
FileInputStream stream = new FileInputStream(newFile);
}

public static void main(String[] args) {


try {
findFile();
}
catch (IOException e) {
[Link](e);
}
}
}

Output

[Link]: [Link] (The system cannot find the file


specified)

When we run this program, if the file [Link] does not exist, FileInputStream throws
a FileNotFoundException which extends the IOException class.

The findFile() method specifies that an IOException can be thrown. The main() method calls this
method and handles the exception if it is thrown.
If a method does not handle exceptions, the type of exceptions that may occur within it must be
specified in the throws clause.

Multiple Catch blocks

For each try block, there can be zero or more catch blocks. Multiple catch blocks allow us to
handle each exception differently.

The argument type of each catch block indicates the type of exception that can be handled by it.
For example,

class ListOfNumbers {
public int[] arr = new int[10];

public void writeList() {

try {
arr[10] = 11;
}

catch (NumberFormatException e1) {


[Link]("NumberFormatException => " + [Link]());
}

catch (IndexOutOfBoundsException e2) {


[Link]("IndexOutOfBoundsException => " +
[Link]());
}

}
}

class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
[Link]();
}
}

Output
IndexOutOfBoundsException => Index 10 out of bounds for length 10

Here, we are trying to assign a value to the index 10.


Hence, IndexOutOfBoundException occurs.

When an exception occurs in the try block,

 The exception is thrown to the first catch block. The first catch block does not handle
an IndexOutOfBoundsException, so it is passed to the next catch block.

 The second catch block in the above example is the appropriate exception handler
because it handles an IndexOutOfBoundsException. Hence, it is executed.

You might also like