Extendig Java Classes
Extendig Java Classes
Exception Handling
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
1. class Bike9{
2.
3.
void run(){
4.
speedlimit=400;
5.
6.
7.
8.
obj.run();
9.
3. }
4.
5. class Honda extends Bike{
6.
7.
8.
9.
10.
honda.run();
11.
12. }
Output:Compile Time Error
5.
6.
7.
8.
honda.run();
9.
10. }
Output:Compile Time Error
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
int rollno;
3.
String name;
4.
String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data members will get memory
each time when object is created.All student have its unique rollno and name so instance data
member is good.Here, college refers to the common property of all objects.If we make it
static,this field will get memory only once.
Java static property is shared to all objects.
int rollno;
5.
String name;
6.
7.
8.
9.
rollno = r;
10.
name = n;
11.
16. }
Output:1
2
3
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
int rollno;
5.
String name;
6.
7.
8.
9.
college = "BBDIT";
10.
11.
12.
13.
rollno = r;
14.
name = n;
15.
16.
17.
18.
19.
20.
Student9.change();
21.
22.
23.
24.
25.
26.
s1.display();
27.
s2.display();
28.
s3.display();
29.
30. }
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
5.
return x*x*x;
6.
7.
8.
9.
int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Output:125
3.
4.
5.
System.out.println(a);
6.
7. }
Output:Compile Time Error
display();
}
static void display() {
System.out.println("Java is my favorite programming language.");
}
}
An interface in java is a blueprint of a class. It has static constants and abstract methods
only. Interface declares a set of methods & their Signatures.
The methods that are declared in an interface should not have implementation codes.
A class that makes use of an interface should provide the codes for the method declared
in that interface.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class
There are mainly two reasons to use interface. They are given below.
The java compiler adds public and abstract keywords before the interface method and public, static
and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public and
abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
Structure of Interface:
Interface_name
{
Type variable-name1=value1;
..
..
Type variable-nameN=valueN;
Return-Type method-Name1(parameter-list);
..
..
Return-Type method-NameN(parameter-list);
}
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the A class.
1. interface printable
2. {
3. void print();
4. }
5.
6. class A6 implements printable{
7. public void print()
8. {
9. System.out.println("Hello");
10. }
11.
12. public static void main(String args[]){
13. A6 obj = new A6();
14. obj.print();
15. }
16. }
Output:Hello
Multiple Inheritance
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
8.
9. class A7 implements Printable, Showable{
10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}
13.
14. public static void main(String args[]){
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
If a class contain any abstract method then the class is declared as abstract class. An abstract
class is never instantiated. It is used to provide abstraction. Although it does not provide 100%
abstraction because it can also have concrete method.
Syntax :
abstract class class_name { }
Method that are declared without any body within an abstract class are called abstract method.
The method body will be defined by its subclass. Abstract method can never be final and static.
Any class that extends an abstract class must implement all the abstract methods declared by the
super class.
Syntax :
abstract return_type function_name ();
// No definition
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
1. abstract class Bike{
2.
3. }
4. class Honda4 extends Bike{
5. void run()
6. {
7. System.out.println("running safely..");
8. }
9. public static void main(String args[]){
10. Bike obj = new Honda4();
11. obj.run();
12. }
13. }
O/p:running safely..
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user)
and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: TestAbstraction1.java
1. abstract class Shape{
2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() meth
od
15. s.draw();
16. }
17. }
drawing circle
File: TestBank.java
1. abstract class Bank{
2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
An abstract class can have data member, abstract method, method body, constructor and even
main() method.
File: TestAbstraction2.java
1. //example of abstract class that have method body
2.
3.
Bike(){System.out.println("bike is created");}
4.
5.
6.
7.
8.
9.
10. }
11. class TestAbstraction2{
12. public static void main(String args[]){
13. Bike obj = new Honda();
14. obj.run();
15. obj.changeGear();
16. }
17. }
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
compile time error
Rule: If you are extending any abstract class that have abstract method, you must either provide the
implementation of the method or make this class abstract.
When to use Abstract Methods & Abstract Class?
Abstract methods are usually declared where two or more subclasses are expected to do a similar
thing in different ways through different implementations. These subclasses extend the same
Abstract class and provide different implementations for the abstract methods.
Abstract classes are used to define generic types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.
Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and methods.
Syntax of Inner class
1. class Java_Outer_class{
2.
//code
3.
class Java_Inner_class{
4.
//code
5.
6. }
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
Description
A class created within class and outside method.
A class created for implementing interface or extending class. Its name is
decided by the java compiler.
A class created within method.
A static class created within class.
An interface created within class or interface.
Enum in Java
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc.
The java enum constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.
enum may implement many interfaces but cannot extend any class because it internally
extends Enum class
The java compiler internally adds the values() method when it creates an enum. The values()
method returns an array containing all the values of the enum.
The enum can be defined within or outside the class because it is similar to a class.
Java enum example: defined outside class
1. enum Season { WINTER, SPRING, SUMMER, FALL }
2. class EnumExample2{
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.println(s);
6. }}
Output:WINTER
System.out.println("sunday");
9.
break;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest
of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed. That is why we use exception handling in java.
Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
Checked Exception
The exception that can be predicted by the programmer.Example : File that need to be
opened is not found. These type of exceptions must be checked at compile time.
Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked
exception are ignored at compile time. Example : ArithmeticException,
NullPointerException, Array Index out of Bound exception. Unchecked exceptions are
checked at runtime.
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Example : if stack overflow occurs, an error will arise. This type of error is not possible
handle in code.
Unchecked Exception
Output :
Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero inside try
block. The program control is transfered outside try block. Thus the line "This line will not be
executed" is never parsed by the compiler. The exception thrown is handle in catch block. Once
the exception is handled the program controls continue with the next line in the program. Thus
the line "After exception is handled" is printed.
A try block can be followed by multiple catch blocks. You can have any number of catch blocks
after a single try block.If an exception occurs in the guarded code the exception is passed to the
first catch block in the list. If the exception type of exception, matches with the first catch block
it gets caught, if not the exception is passed down to the next catch block. This continue until the
exception is caught or falls through all catches.
Output :
divide by zero
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement.
throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions to
handle. A method can do so by using the throws keyword.
Syntax :
type method_name(parameter_list) throws exception_list
{
//definition of method
}
NOTE : It is necessary for all exceptions, except the exceptions of type Error and
RuntimeException, or any of their subclass.
Finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes whether or not exception has occurred. Using a finally block, lets you run
any cleanup type statements that you want to execute, no matter what happens in the protected
code. A finally block appears at the end of catch block.
Output :
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.
You can see in above example even if exception is thrown by the program, which is not handled
by catch block, still finally block will get executed.
User defined Exception subclass
You can also create your own exception sub class simply by extending java Exception class. You
can define a constructor for your Exception sub class (not compulsory) and you can override the
toString() function to display your customized message on catch.
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}
class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
Points to Remember
1. Extend the Exception class to create your own ecxeption class.
2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.