Java Unit II Notes
Java Unit II Notes
// concept of inheritance
// base class
class Bicycle
this.gear = gear;
this.speed = speed;
}
// the Bicycle class has two methods
speed -= decrement;
speed += increment;
+"\n"
// derived class
super(gear, speed);
seatHeight = startHeight;
@Override
return (super.toString()+
// driver class
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
import java.util.*;
import java.lang.*;
import java.io.*;
class one
System.out.println("Geeks");
System.out.println("for");
}
}
// Driver class
g.print_geek();
g.print_for();
g.print_geek();
Output:
Geeks
for
Geeks
import java.util.*;
import java.lang.*;
import java.io.*;
class one
System.out.println("Geeks");
{
System.out.println("for");
System.out.println("Geeks");
// Drived class
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
import java.util.*;
import java.lang.*;
import java.io.*;
class one
System.out.println("Geeks");
System.out.println("for");
/*............*/
// Drived class
g.print_geek();
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
import java.util.*;
import java.lang.*;
import java.io.*;
interface one
interface two
}
class child implements three
@Override
System.out.println("Geeks");
System.out.println("for");
// Drived class
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> {
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
// A simple interface
interface In1
{
// public, static and final
final int a = 10;
// 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.
// 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;
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;
obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the
package.
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.
Example :
// Java program to demonstrate how exception is thrown.
class ThrowsExecp{
}
}
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.
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
}
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
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.