Javanotes Unit-3
Javanotes Unit-3
Inheritance
Definition:
The mechanism of deriving a new class from an old one is called inheritance
The old class is known as the base class or super class or parent class
The new class is known as the sub class or derived class or child class
Types of Inheritance
Single inheritance ( only one super class)
Multiple inheritance ( several super classes)
Hierarchical inheritance ( one super class, many subclasses)
Multilevel inheritance ( derived from a derived class)
Java does not directly implement multiple inheritance
This concept is implemented using a secondary inheritance path in the form of interfaces
Defining a subclass
A subclass is defined as follows:
class subclassname extends superclassname
{
variable declarations;
methods declarations;
}
The keyword extends specifies that the properties of the superclassname are extended to the subclassname
The subclass will now contains its own variables and methods as well those of the superclass
Ex:
class Room
{
int length, breadth;
Room(int x, int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}
{
int height;
class InherTest
{
Subclass constructor
A subclass constructor is used to construct the instance variables of both the subclass and superclass
The subclass constructor uses the keyword super to invoke the constructor method of the superclass
The keyword super is used under the following conditions
Super may only be used within a subclass constructor method
The call to superclass constructor must appear as the first statement within the subclass
constructor
The parameters in the super call must match the order and type of the instance variable declared
in the superclass
Multilevel inheritance
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
the chain ABC is known as inheritance path
2
II SEM JAVA PROGRAMMING 2022
Hierarchical Inheritance
Many programming problems can be cast into a hierarchy where certain features of one level are shared by many
others below the level
Following diagram shows a hierarchical classification of accounts in a commercial bank
Method Overriding
Defining a method in the subclass that has the same name, same arguments and same return type as a method in
the superclass.
When that method is called, the method defined in the subclass is invoked and executed instead of the one in the
superclass .This process is known as method overriding
Ex
class Super
{
int x;
Super(int x)
{
this.x = x;
}
void display() // Method Defined
{
System.out.println(“Super x = “ + x);
}
}
class Sub extends Super
3
II SEM JAVA PROGRAMMING 2022
{
int y;
Sub(int x, int y)
{
super(x);
this.y=y;
}
void display() //Method defined again
{
System.out.println(“Super x = “ + x);
System.out.println(“Sub y = “ + y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1 = new Sub(100, 200);
s1.display();
}
}
class A
{
final float PI = 3.14F;
int rad;
A(int r)
{
rad=r;
}
float area_circle()
{
float area=PI*rad*rad;
//PI=PI+1; Error can’t change value of final variable
return(area);
}
}
public class FinalVar
{
public static void main(String args[])
4
II SEM JAVA PROGRAMMING 2022
{
A a =new A();
float area= a.area_circle(2);
System.out.println(“area of circle is “ + area);
}
}
Final classes
A class that can not be subclassed is called final class
This is achieved by using the keyword final as follows:
final class A { ……… }
final class B extends C { ………. }
Any attempt to inherit these classes will cause an error and the compiler will not allow it
Declaring a class final prevents any unwanted extensions to the class
{
System.out.println("Illegal");
}
}
public class FinalClass
{
public static void main(String[] args)
{
B b =new B();
b.method1();
}
}
Ex:
abstract class A
{
-----
abstract void display();
-----
}
While using the abstract classes, the following conditions must be satisfied
We can not use abstract classes to instantiate objects directly
Ex:
A a = new A();
is illegal because A is an abstract class
The abstract methods of an abstract class must be defined in its subclass
We cannot declare abstract constructors or abstract static methods
Example for Abstract Class and Abstract Method
abstract class A
{
abstract void callme();
void callmetoo()
{
System.out.println("THIS IS A CONCRETE METHOD");
}
}
class B extends A
{
void callme()
{
6
II SEM JAVA PROGRAMMING 2022
7
Packages:
A Package can be defined as a grouping of related types(classes, interfaces)
A package represents a directory that contains related group of classes and interfaces.
Packages are used in Java in order to prevent naming conflicts.
There are two types of packages in Java.
Pre-defined Packages(built-in)
User defined packages
Pre-defined Packages:
Package Description
Name
Contains language support classes (for e.g classes which definesprimitive
java.lang data types, math operations, etc.). This package is automatically imported.
Contains utility classes which implement data structures like Linked List,
java.util Hash Table, Dictionary, etc and support for Date / Time operations. This
package is also called as Collections.
java.applet Contains classes for creating Applets.
This package helps to develop GUI like java.awt. The ‘x’ in javax represents
javax.swing that it is an extended package which means it is a package developed from
another package by adding new features to it. In fact,
javax.swing is an extended package of java.awt.
This package helps to connect to databases like Oracle/Sybase/Microsoft
java.sql Access to perform different operations.
package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a; y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
}
Access Protection
Access protection defines actually how much an element (class, method, variable) isexposed to other
classes and packages.
There are four types of access specifiers available in java:
Visible to the class only (private).
Visible to the package (default). No modifiers are needed.
Visible to the package and all subclasses (protected)
Visible to the world (public)
Example:
The following example shows all combinations of the access control modifiers. This example has two
packages and five classes. The source for the first package defines threeclasses: Protection, Derived, and
SamePackage.
Name of the package: pkg1
This file is Protection.javapackage pkg1;
public class Protection
{
int n = 1;
private int n_priv = 2; protected int n_prot = 3;public int n_publ = 4;
public Protection()
{
System.out.println("base constructor"); System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv); System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}
/* class only
* System.out.println("n_priv = "4 + n_priv); */
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
/* class only
System.out.println("n_priv = " + n_priv); */
class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();
System.out.println("other package - Non sub class constructor");
/* class or package only System.out.println("n = " + pro.n); */
If you want to try these t two packages, here are two test files you can use. The one forpackage pkg1 is
shown here:
Advantages of interfaces:
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritances.
Syntax:
access_specifier interface interfae_name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Implementing Interfaces:
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and thencreate the methods
defined by the interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface1 [,interface2...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma.
The methods that implement an interface must be public. Also, the type signature of implementing method must
match exactly the type signature specified in interface definition.
void call();
}
Variables in Interfaces:
We can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values. When we include that
interface in a class (that is, when you “implement” the interface), all of those variable names
will be in scope as constants. (This is similar to using a header file in C/C++ to create a large
number of #defined constants or const declarations). If an interface contains no methods, then
any class that includes such an interface doesn’t actually implement anything. Itis as if that
class were importing the constant fields into the class name space as final variables.
Example: Java program to demonstrate variables in interface.interface left
{
int i=10;
}
interface right
{
int i=100;
}
class Test implements left,right
{
public static void main(String args[])
{
System.out.println(left.i);//10 will be printed System.out.println(right.i);//100 will be printed*/
}
}
}
}
class Class_Interface
{
public static void main(String arh[])
{
College c=new College();c.display1();
c.display2();
c.display3();
}
}
Example 2: Java program to implement interface and inheriting the properties from a class.
interface Teacher
{
void display1();
}
class Student
{
void display2()
{
System.out.println("Hi I am Student");
}
}
class College extends Student implements Teacher
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
}
class Interface_Class
{
public static void main(String arh[])
{
College c=new College();c.display1();
c.display2();
}
}
Difference between Interface and Abstract class:
Abstract Class Interface
Or
An abnormal condition that disrupts Normal program flow.
There are many cases where abnormal conditions happen during program execution, such as
Trying to access an out - of –bounds array elements.
The file you try to open may not exist.
The file we want to load may be missing or in the wrong format.
The other end of your network connection may be non –existence.
If these cases are not prevented or at least handled properly, either the program will be aborted
abruptly, or the incorrect results or status will be produced.
When an error occurs with in the java method, the method creates an exception object and hands it off
to the runtime system.
The exception object contains information about the exception including its type and the state of the
program when the error occurred. The runtime system is then responsible for finding some code to
handle the error.
In java creating an exception object and handling it to the runtime system is called throwing an
exception.
Exception is an object that is describes an exceptional ( i.e. error) condition that has occurred in a piece
of code at run time.
When a exceptional condition arises, an object representing that exception is created and thrown in the
method that caused the error. That method may choose to handle the exception itself, or pass it on.
Either way, at some point, the exception is caught and processed.
Exceptions can be generated by the Java run-time system, or they can be manually generated by your
code.
System generated exceptions are automatically thrown by the Java runtime system
For Example:
class Exc0 {
public static void main(String args[])
{ int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of Exc0 to stop, because once an
exception has been thrown, it must be caught by an exception handler and dealt
with immediately. In this example, we haven’t supp the exception is caught by the default handler provided by
the Java run-time system. Any
exception that is not caught by your program will ultimately be processed by the default handler. The default
handler displays a string describing the exception, prints a stack trace from the point at which the exception
occurred, and terminates the program. Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Notice how the class name, Exc0; the method name, main; the filename, Exc0.java; and the line number, 4
Output
Out of the Range Quit
Program 2 Class ArithExce
{
Public static void main(String args[])
{
Int a=10; Int b=0; Try
{
a=a/b; System.out.println(―Won’t Print‖);
}
Catch(ArithmeticException e)
{
System.out.println(―Division by Zero error‖); System.out.println(―Change the b value‖);
}
System.out.println(―Quit‖);
}
}
Output
Division By zero error Please change the B value Quit
Note:
A try ad its catch statement form a unit. We cannot use try block alone.
The compiler does not allow any statement between try block and its associated catch block
Displaying description of an Exception
Throwable overrides the toString() method (defined by Object) so that it returns a string containing a description
of the exception.
We can display this description in a println statement by simply passing the exception as an argument.
catch (ArithmeticException e) { System.out.println("Exception: " + e); a = 0; // set a to zero and continue
}
When this version is substituted in the program, and the program is run, each divide-by- zero error displays the
following message:
– Exception: java.lang.ArithmeticException: / by zero
Multiple Catch Blocks
In some cases, more than one exception could be raised by a single piece of code. To handle this type of
situation, you can specify two or more catch clauses, each catching a different type of exception. When an
exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the
exception is executed. After one catch statement executes, the others are bypassed, and execution continues after
the try/catch block. The following example traps two different exception types:
Throw Keyword
So far, we have only been catching exceptions that are thrown by the Java Run –Time systems. How ever, it is
possible for our program to throw an exception explicitly, using the throw statement.
Throw throwableInstance
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such
as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions
There are two ways you can obtain a Throwable object:
– using a parameter into a catch clause
– creating one with the new operator.
The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the
exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try
statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the
program and prints the stack trace
// Demonstrate throw. class ThrowDemo { static void demoproc()
{ try {
throw new NullPointerException("demo");
} catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the
exception
}
}
public static void main(String args[])
{ try
{
demoproc();
} catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}}
This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then
calls demoproc( ). The demoproc( ) method then sets up another exception-handling context and immediately
throws a new instance of NullPointerException, which is caught on the next line. The exception is then
rethrown. Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of J close attention to this line:
throw new NullPointerException("demo");
Here, new is used to construct an instance of NullPointerException. All of- Java’ in run-time exceptions have at
least two constructors: one with no parameter and one that
takes a string parameter. When the second form is used, the argument specifies a string that describes the
exception. This string is displayed when the object
is used as an argument to print( ) or println( ). It can also be obtained by a call to
getMessage( ), which is defined by Throwable.
Throws Keyword
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers
of the method can guard themselves against that exception. You
do this by including a throws clause in the method’sthrowsclauselistsdeclar the types of exceptions that a
method might throw. This is necessary for all exceptions,
except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method
can throw must be declared in the throws clause. If they are not, a compile-time error will result. This is the
general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw
Program
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{ System.out.println("Inside throwOne."); throw new IllegalAccessException("demo");
}
public static void main(String args[]) { try {
throwOne();
} catch (IllegalAccessException e)
{ System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException
Finally block
Throws is followed by class.
Throws is used with the method signature.
You can declare multiple exceptions e.g. public void method()throws IOException,SQLException.
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear
path that alters the normal flow through the method. Depending upon how the method is coded, it is even
possible for an exception to cause the method to return prematurely.
This could be a problem in some methods. For example, if a method
opens a file upon entry and closes it upon exit, then you will not want the code that closes the file to be bypassed
by the exception-handling mechanism. The finally keyword is designed to address this contingency.
finally creates a block of code that will be executed after a try/catch block has completed and before the code
following the try/catch block. The finally block will execute whether or not an exception is thrown. If an
exception is thrown, the finally block will execute even if no catch statement matches the exception. Any time a
method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit
return statement, the finally clause is also executed just before the method returns. This can be useful for closing
file handles and freeing up any other resources that might have been allocated at the beginning of a method with
the intent of disposing of them before returning. The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
// Demonstrate finally. class FinallyDemo {
// Through an exception out of the method. static void procA() {
try {
System.out.println("inside procA"); throw new RuntimeException("demo");
} finally { System.out.println("procA's finally");
}
}
// Return from within a try block. static void procB() { try {
System.out.println("inside procB"); return;
} finally { System.out.println("procB's finally");
}
}
// Execute a try block normally. static void procC() {
try {
System.out.println("inside procC"); } finally { System.out.println("procC's finally");
}
}
public static void main(String args[]) { try {
procA();
} catch (Exception e) { System.out.println("Exception caught");
}
procB();
procC();
}
}
In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally clause is
executed on the way out. procB( )’stry statement is exited via a return statement. The finally clause is executed
before procB( ) returns. In procC( ), the try statement executes normally, without error. However, the finally
block is still executed. If a finally block is associated with a try, the finally block will be executed upon
conclusion of the try.
Here is the output generated by the preceding program: inside procA
procA’s finally Exception caught
inside procB
procB’s finally inside procC procC’sly final
Java final example
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error 5. }}
Output:
Exception caught Marks is > 100 End of program
Multithreaded Programming
1
MULTITHREADING
Introduction
2
11
stop
start
Active Thread
stop Dead Killed
suspend resume
stop
sleep notify
wait
start stop
Runnable Dead
state state
Runnable state
This state means that the thread is ready for
execution and is waiting for the availability of
the processor
yield
. . . .
Running Thread
Running State
Running means that the processor has given
its time to the thread for its execution
. . .
suspended
Runnable
Running
2. It has been made to sleep. We can put a thread
to sleep for a specified time period using the
method sleep(time) where time is in milliseconds.
This means that the thread is out of the queue
during this time period. The thread re-enters the
runnable state as soon as this time period is
elapsed
sleep(t)
. after(t)
. .
Running Suspended
Runnable
3. It has been told to wait until some event occurs. This
is done using the wait() method. The thread can be
scheduled to run again using the notify() method
wait
. notify
. .
Running Waiting
Runnable
Blocked Thread
a thread is said to be blocked when it is prevented
from entering into the runnable state and
subsequently the running state
It is a natural death
Method Meaning
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Main Thread Intertrupted");
}
}
}
30
class RunnableDemo1
{
public static void main(String args[])
{
new NewThread();
try
{
for(int i=5;i>0;i--)
{
System.out.println("main Thread:"+i);
Thread.sleep(1000);
}
}
37
catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}
System.out.println("Main thread exiting.");
}
}
Extending Thread
38
catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}
System.out.println("Main thread exiting.");
}
}
Creating Multiple Threads
49
Ex:
synchronized void update()
{
----------
63
same object.
notifyAll( ) wakes up all the threads that called wait(
Problem
To make sure that the producer won’t try to
add data into the buffer if it’s full and that the
consumer won’t try to remove data from an
empty buffer.
73
Solution
The producer is to either go to sleep or discard data if the
buffer is full.
The next time the consumer removes an item from the