0% found this document useful (0 votes)
2 views

Java Unit II Notes

The document provides a comprehensive overview of inheritance in Java, detailing its significance in object-oriented programming and explaining key concepts such as superclasses, subclasses, and various types of inheritance including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. It also discusses the role of interfaces, packages, and their importance in Java programming, highlighting how they facilitate code organization, reusability, and abstraction. Additionally, it covers the syntax and practical examples to illustrate these concepts effectively.

Uploaded by

priyankavelu0403
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Unit II Notes

The document provides a comprehensive overview of inheritance in Java, detailing its significance in object-oriented programming and explaining key concepts such as superclasses, subclasses, and various types of inheritance including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. It also discusses the role of interfaces, packages, and their importance in Java programming, highlighting how they facilitate code organization, reusability, and abstraction. Additionally, it covers the syntax and practical examples to illustrate these concepts effectively.

Uploaded by

priyankavelu0403
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Inheritance in Java

Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism


in java by which one class is allow to inherit the features(fields and methods) of another
class.
Important terminology:
● Super Class: The class whose features are inherited is known as super class(or a base
class or a parent class).
● Sub Class: The class that inherits the other class is known as sub class(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.
● he keyword used for inheritance is extends.
Syntax :
● class derived-class extends base-class
● {
● //methods and fields
● }
● Example: In below example of inheritance, class Bicycle is a base class, class
MountainBike is a derived class which extends Bicycle class and class Test is a
driver class to run program.
//Java program to illustrate the

// concept of inheritance

// base class

class Bicycle

// the Bicycle class has two fields

public int gear;

public int speed;

// the Bicycle class has one constructor

public Bicycle(int gear, int speed)

this.gear = gear;

this.speed = speed;

}
// the Bicycle class has two methods

public void applyBrake(int decrement)

speed -= decrement;

public void speedUp(int increment)

speed += increment;

// toString() method to print info of Bicycle

public String toString()

return("No of gears are "+gear

+"\n"

+ "speed of bicycle is "+speed);

// derived class

class MountainBike extends Bicycle

// the MountainBike subclass adds one more field

public int seatHeight;

// the MountainBike subclass has one constructor

public MountainBike(int gear,int speed,


int startHeight)

// invoking base-class(Bicycle) constructor

super(gear, speed);

seatHeight = startHeight;

// overriding toString() method

// of Bicycle to print more info

@Override

public String toString()

return (super.toString()+

"\nseat height is "+seatHeight);

// driver class

public class Test

public static void main(String args[])

MountainBike mb = new MountainBike(3, 100, 25);

System.out.println(mb.toString());

Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
Illustrative image of the program:

In practice, inheritance and polymorphism are used together in java to achieve fast
performance and readability of code.
Types of Inheritance in Java
Below are the different types of inheritance which is supported by Java.
1. Single Inheritance : In single inheritance, subclasses inherit the features of one
superclass. In image below, the class A serves as a base class for the derived class B.
//Java program to illustrate the

// concept of single inheritance

import java.util.*;

import java.lang.*;

import java.io.*;

class one

public void print_geek()

System.out.println("Geeks");

class two extends one

public void print_for()

System.out.println("for");

}
}

// Driver class

public class Main

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 act as the base class to other class. In
below image, the 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.
// Java program to illustrate the

// concept of Multilevel inheritance

import java.util.*;

import java.lang.*;

import java.io.*;

class one

public void print_geek()

System.out.println("Geeks");

class two extends one

public void print_for()

{
System.out.println("for");

class three extends two

public void print_geek()

System.out.println("Geeks");

// Drived class

public class Main

public static void main(String[] args)

three g = new three();

g.print_geek();

g.print_for();

g.print_geek();

Output:
Geeks
for
Geeks
3. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one sub class.In below image, the class A serves as a base
class for the derived class B,C and D.
// Java program to illustrate the

// concept of Hierarchical inheritance

import java.util.*;

import java.lang.*;

import java.io.*;

class one

public void print_geek()

System.out.println("Geeks");

class two extends one

public void print_for()


{

System.out.println("for");

class three extends one

/*............*/

// Drived class

public class Main

public static void main(String[] args)

three g = new three();

g.print_geek();

two t = new two();

t.print_for();

g.print_geek();

Output:
Geeks
for
Geeks
4. Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have
more than one superclass and inherit features from all parent classes. Please note that
Java does not support multiple inheritance with classes. In java, we can achieve
multiple inheritance only through Interfaces. In image below, Class C is derived from
interface A and B.
// Java program to illustrate the

// concept of Multiple inheritance

import java.util.*;

import java.lang.*;

import java.io.*;

interface one

public void print_geek();

interface two

public void print_for();

interface three extends one,two

public void print_geek();

}
class child implements three

@Override

public void print_geek() {

System.out.println("Geeks");

public void print_for()

System.out.println("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(Through Interfaces) : It is a mix of two or more of the above types
of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid
inheritance is also not possible with classes. In java, we can achieve hybrid inheritance
only through Interfaces.
Important facts about inheritance in Java
● Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.
● Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by
java.
● Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from the
subclass.
● Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters
and setters) for accessing its private fields, these can also be used by the subclass.
What all can be done in a Subclass?
In sub-classes we can inherit members as is, replace them, hide them, or supplement them
with new members:
● The inherited fields can be used directly, just like any other fields.
● We can declare new fields in the subclass that are not in the superclass.
● The inherited methods can be used directly as they are.
● We can write a new instance method in the subclass that has the same signature as the
one in the superclass, thus overriding it (as in example above, toString() method is
overridden).
● We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
● We can declare new methods in the subclass that are not in the superclass.
● We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.
Interfaces in Java
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
● Interfaces specify what a class must do and not how. It is the blueprint of the class.
● An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set
of methods that the class has to implement.
● If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
● A Java library example is, Comparator Interface. If a class implements this interface,
then it can be used to sort a collection.
Syntax :
interface <interface_name> {

// declare constant fields


// declare methods that abstract
// by default.
}

To declare an interface, use interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all
fields are public, static and final by default. A class that implement interface must implement
all the methods declared in the interface. To implement interface use implements keyword.
Why do we use interface ?
● It is used to achieve total abstraction.
● Since java does not support multiple inheritance in case of class, but by using interface
it can achieve multiple inheritance .
● It is also used to achieve loose coupling.
● Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in
interface are final, public and static.
// A simple interface
interface Player
{
final int id = 10;
int move();
}
To implement an interface we use keyword: implement

// Java program to demonstrate working of


// interface.
import java.io.*;

// A simple interface
interface In1
{
// public, static and final
final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1
{
// Implementing the capabilities of
// interface.
public void display()
{
System.out.println("Geek");
}

// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Output:
Geek
10
Packages In Java
Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. Packages are used for:
● Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
● Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
● Providing controlled access: protected and default have package level access control.
A protected member is accessible by classes in the same package and its subclasses.
A default member (without any access specifier) is accessible by classes in the same
package only.
● Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an
import class from existing packages and use it in our program. A package is a container of a
group of related classes where some of the classes are accessible are exposed and others
are kept for internal purpose.
We can reuse existing classes from the packages as many time as we need it in our
program.
How packages work?
Package names and directory structure are closely related. For example if a package name
is college.staff.cse, then there are three directories, college, staff and cse such that cse is
present in staff and staff is present college. Also, the directory college is accessible
through CLASSPATH variable, i.e., path of parent directory of college is present in
CLASSPATH. The idea is to make sure that classes are easy to locate.
Package naming conventions : Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.

Adding a class to a Package : We can add more classes to a created package by using
package name at the top of the program and saving it in the package directory. We need a
new java file to define a public class, otherwise we can add the new class to an
existing .java file and recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are
not imported by default, they have to imported explicitly. Also, members of a subpackage
have no access privileges, i.e., they are considered as different package for protected and
default access specifiers.
Example :
import java.util.*;
util is a subpackage created inside java package.

Accessing classes inside a package


Consider following two statements :
/ import the Vector class from util package.
import java.util.vector;

// import all the classes from util package


import java.util.*;
● First Statement is used to import Vector class from util package which is contained
inside java.
● Second statement imports all the classes from util package.
// All the classes and interfaces of this package
// will be accessible but not subpackages.
import package.*;

// Only mentioned class of this package will be accessible.


import package.classname;

// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.packag.Date;
// Java program to demonstrate accessing of members when
// corresponding classes are imported and not imported.
import java.util.Vector;

public class ImportDemo


{
public ImportDemo()
{
// java.util.Vector is imported, hence we are
// able to access directly in our code.
Vector newVector = new Vector();

// java.util.ArrayList is not imported, hence


// we were referring to it using the complete
// package.
java.util.ArrayList newList = new java.util.ArrayList();
}

public static void main(String arg[])


{
new ImportDemo();
}
}
Types of packages:

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;

public class PrintName


{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";

// Creating an instance of class MyClass in


// the package.
MyClass obj = new MyClass();

obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the
package.

Using Static Import


Static import is a feature introduced in Java programming language ( versions 5 and above )
that allows members ( fields and methods ) defined in a class as public static to be used in
Java code without specifying the class in which the field is defined.
Following program demonstrates static import :

// Note static keyword after import.


import static java.lang.System.*;

class StaticImportDemo
{
public static void main(String args[])
{
// We don't need to use 'System.out'
// as imported using static.
out.println("GeeksforGeeks");
}
}
Output:
GeeksforGeeks
Directory structure
The package name is closely associated with the directory structure used to store the
classes. The classes (and other entities) belonging to a specific package are stored together
in the same directory. Furthermore, they are stored in a sub-directory structure specified by
its package name. For example, the class Circle of package com.zzz.project1.subproject2 is
stored as “$BASE_DIR\com\zzz\project1\subproject2\Circle.class”, where $BASE_DIR
denotes the base directory of the package. Clearly, the “dot” in the package name
corresponds to a sub-directory of the file system.
The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the
Java compiler and runtime must be informed about the location of the $BASE_DIR so as to
locate the classes. This is accomplished by an environment variable called CLASSPATH.
CLASSPATH is similar to another environment variable PATH, which is used by the
command shell to search for the executable programs.
Setting CLASSPATH:
CLASSPATH can be set by any of the following ways:
● CLASSPATH can be set permanently in the environment: In Windows, choose control
panel ? System ? Advanced ? Environment Variables ? choose “System Variables” (for
all the users) or “User Variables” (only the currently login user) ? choose “Edit” (if
CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the variable name ?
Enter the required directories and JAR files (separated by semicolons) as the value
(e.g., “.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”). Take note that you need to
include the current working directory (denoted by ‘.’) in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
● > SET CLASSPATH
● CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
● > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-
api.jar
● Instead of using the CLASSPATH environment variable, you can also use the command-
line option -classpath or -cp of the javac and java commands, for example,
● > java –classpath c:\javaproject\classes
com.abc.project1.subproject2.MyClass3
Important Points
1. Every class is part of some package.
2. If no package is specified, the classes in the file goes into a special unnamed package
(the same unnamed package for all files).
3. All classes/interfaces in a file are part of the same package. Multiple files can specify
the same package name.
4. If package name is specified, the file must be in a subdirectory called name (i.e., the
directory name must match the package name).
5. We can access public classes in another (named) package using: package-
name.class-name
Exceptions in Java
What is an Exception?
An 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.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not
try to catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base
class of hierarchy.One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception.Another branch,Error are used by the Java run-time
system(JVM) to indicate errors having to do with the run-time environment
itself(JRE). StackOverflowError is an example of such an error.

For checked vs unchecked exception, see Checked vs Unchecked Exceptions


How JVM handle an Exception?
Default Exception Handling : Whenever inside a method, if an exception has
occurred, the method creates an Object known as Exception Object and hands it off
to the run-time system(JVM). The exception object contains name and description of
the exception, and current state of the program where exception has occurred.
Creating the Exception Object and handling it to the run-time system is called
throwing an Exception.There might be the list of the methods that had been called to
get to the method where exception was occurred. This ordered list of the methods is
called Call Stack.Now the following procedure will happen.
● The run-time system searches the call stack to find the method that contains
block of code that can handle the occurred exception. The block of the code is
called Exception handler.
● The run-time system starts searching from the method in which exception
occurred, proceeds through call stack in the reverse order in which methods
were called.
● If it finds appropriate handler then it passes the occurred exception to it.
Appropriate handler means the type of the exception object thrown matches the
type of the exception object it can handle.
● If run-time system searches all the methods on call stack and couldn’t have
found the appropriate handler then run-time system handover the Exception
Object to default exception handler , which is part of run-time system. This
handler prints the exception information in the following format and terminates
program abnormally.
● Exception in thread "xxx" Name of Exception : Description

● ... ...... .. // Call Stack


See the below diagram to understand the flow of the call stack.

Example :
// Java program to demonstrate how exception is thrown.
class ThrowsExecp{

public static void main(String args[]){


String str = null;
System.out.println(str.length());

}
}
Output :
Exception in thread "main" java.lang.NullPointerException
at ThrowsExecp.main(File.java:8)
How Programmer handles an exception?
Customized Exception Handling : Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally. Briefly, here is how they work.
Program statements that you think can raise exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown. Your code can catch
this exception (using catch block) and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system. To
manually throw an exception, use the keyword throw. Any exception that is thrown
out of a method must be specified as such by a throws clause. Any code that
absolutely must be executed after a try block completes is put in a finally block.

Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more
parts of a program for maximum utilization of CPU. Each part of such program is
called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms :


1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the
run() method available in the Thread class. A thread begins its life inside run()
method. We create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread object.
Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
utput :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

Thread creation by implementing the Runnable Interface

We create a new class which implements java.lang.Runnable interface and override


run() method. Then we instantiate a Thread object and call start() method on this
object.
/ Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<n; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

Thread Class vs Runnable Interface

1. If we extend the Thread class, our class cannot extend any other class because
Java doesn’t support multiple inheritance. But, if we implement the Runnable
interface, our class can still extend other base classes.

2. We can achieve basic functionality of a thread by extending Thread class because


it provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.

You might also like