final void join () – The isAlive () method occasionally useful as continuously checking the value returned by this method and then sleeping makes a very inefficient use of the CPU time. So a better alternative to wait for a thread to die is to use join () method of the Thread class. [Read more…] about Join() Method in Java Example
isAlive() in Java Example
In order to make sure that the main thread finishes last, we introduced a long enough delay by calling the sleep () method within the main() method so that all other threads finish before the main thread. But this of course is hardly a satisfactory solution because if your estimate for the time delay is too short then other threads could finish after the main thread finishes. Therefore, the Thread class provide method isAli ve () to determine if a thread has ended . [Read more…] about isAlive() in Java Example
Creating Thread Using Runnable Interface in Java Example
Another way to create a thread in Java is to define a class that implements the Runnable interface. The previous technique of creating threads by extending the Thread class does not work when you want a class that extends another class and can also run as a thread. It is because java supports only single inheritance, i.e., does not allow a class to extend more than one class. So in such a case implement the Runnable interface. The Runnable interface declares only one method run () that contains the code executed when the thread started. Therefore, if you define a class that implements the Runnable interface, then it must implement the run () method. [Read more…] about Creating Thread Using Runnable Interface in Java Example
Constructors and Methods of the Thread Class in Java with Example
In this Example, we shows how the constructors and methods of the Thread class are used. Here, we have created a subclass MyThread that extends Thread class. This class consists of a field which stores the time in milliseconds for which the thread will sleep. It also contains a parameterized constructor that contains two parameters str of String type and d of int type. This constructor calls the superclass constructor that sets the Thread’s name to the value passed in str and delay field is set to value passed in d. [Read more…] about Constructors and Methods of the Thread Class in Java with Example
Java Thread | Creating Threads and Multithreading in Java
Java Thread: One of the dominant features of the Java language is that it provides built-in support for multithreading – the concurrent running of multiple threads within the same program. Creating a thread in Java is relatively easy. Unlike the old fashioned programming languages, where you have to invoke system-dependent procedures and functions to implement multithreading, in Java, it is no harder than creating an instance of other classes. [Read more…] about Java Thread | Creating Threads and Multithreading in Java
Chained Exceptions in Java Example
Sometimes a catch block catches one exception type and then throws a new exception with additional information. This is known as chained exception. This feature allows you to associate another exception with an exception. The second exception describes the cause of the firstexception. [Read more…] about Chained Exceptions in Java Example
Defining Your Own Exception Class Java Example
So far you have been using the pre-defined exception classes provided by the Java API. However, if you encounter a problem that cannot be adequately described by the predefined exception classes, you can create your own exception class. [Read more…] about Defining Your Own Exception Class Java Example
Nested Try Statements in Java Examples
So far we have been using just single try statement. However, it is possible to nest a try statement inside another try statement. If one try block does not have a corresponding catch block that handles the exception, Java will search the next outer try block for a catch block that will handle the exception, back through successive nesting. If the Java cannot find the catch block for the exception, it will pass the exception to its default exception handler. [Read more…] about Nested Try Statements in Java Examples
Finally Block in Java with Example
If an exception occurs inside a try block and there is no matching catch block, the method terminates without further executing any lines of code from that method. For example, suppose you may want to close a file that has been opened even if your program could not read from the file for some reason. In other words, you want to close the file irrespective whether the read is successful or not. If you want that some lines of code must be executed regardless of whether or not there is matching catch block, put those lines inside the finally block. [Read more…] about Finally Block in Java with Example
Throws Clause in Java Example
The basic principle of Java error handling mechanism is that an exception must either be handled by the method in which it is raised or passed along the call chain for another method to handle it. Suppose a method throws an exception, that is neither a subclass of RuntimeException nor of Error i.e. if it throws a checked exception, then Java requires that the method either handles it or declares it. If the method does not handle the checked exception then the method must declare it using the throws keyword. [Read more…] about Throws Clause in Java Example
Rethrowing Exceptions Java Example
There might be situations in your program where you want to both catch an exception in your code and also want its caller be notified about the exception. This is possible by rethrowing the exception using throw statement. [Read more…] about Rethrowing Exceptions Java Example
Throw Clause Example in Java
You can also throw an exception explicitly. This is accomplished using the throw statement. A throw statement is executed to indicate that an exception has occurred. The exception that you throw using the throw statement can either be the standard system exception or the one that are created by you. The syntax of throw statement is as follows, [Read more…] about Throw Clause Example in Java
Throwable Class Example in Java
The Throwable class provides the following commonly used methods.
• String getMessage (): It returns the description of the exception. It includes fully qualified name of the Exception class and a brief description of the exception. [Read more…] about Throwable Class Example in Java
Stack Trace in Java Example
When an exception is thrown in your program, you can find the exact statement in your program that caused the exception to occur by examining the lines that are displayed right after the line that indicates which exception was encountered. These lines of information that are displayed when an exception occurs is known as Stack trace. It lists the different methods that the exception passed through before your program was completely aborted. Each line in the stack trace contains not only the method name and the corresponding classname but also the name of the source file that contains the class and the line number where the exception occurred. [Read more…] about Stack Trace in Java Example
Multiple Catch Blocks in Java Example
Typically, code in a try-block can throw more than one kind of exception. If this is the case then you can put several catch blocks after the try block to handle them, one for each possible exception. When an exception is generated, the JVM searches the catch blocks in order. The first catch block with a parameter that matches the exception thrown will execute, any remaining catch blocks will be skipped. [Read more…] about Multiple Catch Blocks in Java Example
DivideByZeroException Java Example
Exception handling is a technique of processing problems that occur during the execution of the program. Using exception handling, we can test the code and avoid it from exiting abruptly. [Read more…] about DivideByZeroException Java Example
varargs – Variable-Length Arguments Method in Java Example
Variable-Length Arguments Method in short varargs methods, Such methods usefulness comes into picture when you have a method that can accept a variety of arbitrary data types.
The syntax of a method that accepts a variable number of arguments is as follows:
returnType methodName ( typeName … paraName)
{
………………..
}
Here, paraName is the name of the parameter representing an array of typeName and the ellipsis (m) between typeName and paraName specifies that paraName is actually to be treated as array of zero or more elements of type typeName. Keep in mind that only one variable length parameter may be specified in a method, and may only appear on the last parameter in the list. Regular parameters may precede it.
Now let us consider a program to understand the concept of variable-length arguments. For this, we make a program to calculate average of integer numbers.
public class VarargsMethods
{
public static void main(String[] args)
{
average(15,100);
average(15,100,150);
average(15,100,105,210);
}
static void average(int...num)
{
double sum=0, avg;
int i;
for( i=0; i<num.length; i++)
{
sum += num[i];
}
avg = sum/num.length;
System.out.println("Average = " +avg);
}
}
Static nested class in Java with Example
Java platform provides you to define a class within another class. Such a class is known as nested class. The class that holds the nested class is known as Outer class. It is merely a convenient way of grouping two or more classes together into a single unit or module. A class that contains a nested class is known as the enclosing or outer class of the nested class. In java, We can’t use the static keyword with a class unless it is an Inner class(or non-static nested class), but we can make a nested class static in Java.
Nested classes are used for a variety of purposes such as
• GUI event handling.
• Hiding a class from other classes in the same package.
• As helper classes to perform some specific function ( such as implementing a particular action) or to provide a particular view onto some data (by providing an iterator or enumerator.)
• An object of the inner class can access the implementation of the object that created it, including data that would otherwise be private.
• Allows implementing the same interface more than once in a class.
• Make the code more readable and maintainable as it placed closer to where it used.
Nested classes are divided into two categories: Static nested classes and non-static nested classes. Non-static nested classes are also called inner classes. The Inner classes can further classify into three types: Regular inner classes, Locale inner classes, and Anonymous inner classes.
A static nested class or a top-level class is a class that is declared inside another class with a static modifier. Like static methods, a static nested class can only refer directly to static members of the enclosing classes, even if those members are private. That is, it cannot refer to members of its enclosing class directly.
The following example demonstrates the use of static nested class.
public class OuterClassName {
public static class InnerClassName {
// body of static nested class
}
// More members of outside class
}
Nested classes generally made static when they have a strong relationship with the enclosing class, but their existence is independent of an instance of the enclosing class. Unlike inner classes, you can instantiate the static nested class even if you have not instantiated the outer class. For example:
OuterClassName.InnerClassName = new OuterClassName.InnerClassName();
The following program demonstrates the use of static nested class.
class outer
{
private double i = 11.7 ;
private static String str = "Hi Programmers";
static class inner
{
int j ;
public void display()
{
j = 51;
System.out.println("j = " + j);
//System.out.prinln("i = " + i); illegal statement
System.out.println("str = " + str);
}
}
}
class StaticClass
{
public static void main(String[] args)
{
outer.inner innobj =new outer.inner();
//create instance of //static nested class
innobj.display();
}
}
Explanation: As static keyword is used in the innerclass so it is a static class. The str variable is declared static so it can be accessed in the static class. The variable i is not declared static so it cannot be accessed in the class.
What are the differences between static and non-static nested classes?
Following are the differences between static nested class and non-static nested class. A non-static nested class is also called Inner Class.
• These are non-static members classes. Whereas non-static inner classes defined as instance members of other classes just like an instance variable and method members defined in a class. An instance of non-static inner class always has an instance of the enclosing class associated with it.
• A static nested class doesn’t have a reference of Outer class, but Inner class(or non-static nested class) requires a reference of Outer class. You can not create an instance of Non-static nested class without creating an instance of Outer class.
• The non-static nested class can access all members static and non-static members of Outer class. A static class cannot access all members of the Outer class. It can access only static members of Outer class.
Anonymous Inner Class in Java with Example
Sometimes you need a pure class, and to be instantiated only once in your code. When this is the case, you can use an anonymous inner class. It is called an inner class because it defined inside another class.
Anonymous inner class are the local inner classes that declared without a name, but an object of this class can be created. All of the code for the anonymous class is coded within the method where we need to create an instance of the anonymous class. Since anonymous inner classes do not have a name so you cannot use the new keyword in the usual way to create an instance of the class. Anonymous inner classes are declared and instantiated at the same time.
Anonymous inner classes can also be used to provide a similar facility as that provided by inner classes. Although anonymous inner classes result in more compact programs but they do make the code more difficult to read.
Anonymous Inner Class Properties
Anonymous inner classes defined within methods rather than being members of an outer class. They are local to the methods, and you cannot mark them with any access modifier, like static, public, or private, like local method variables.
Anonymous inner classes always have to either implement interfaces or extend superclasses. You do not need to use the keywords implement or extends when you declare it. The anonymous inner class has to implement every abstract method in the interface or superclass.
Anonymous inner classes always use the no-arg, default constructor out of their superclasses to create instances. If the anonymous inner class used for the implementation of interfaces, they use java.lang.object().
Anonymous inner cases are compiled into classes called OuterClass- Namre$n.class – n is the running number of the inner classes inside the outer classes.
The advantage of using anonymous inner class fro event handling is that you can avoid large if-else statements to decide which component is being handled. Each component gets its own event handler so each event handler knows implicitly the component for which it is working.
We use the following syntax to construct instances of anonymous inner classes:
new SuperClassName/InterfaceName() {
// extends superclass or implements interface
// invoke the default no-arg constructor or Object[]
// Implement abstract methods in superclass/interface
// More methods if necessary……
}
The new operator followed by the name of an existing class or interface, followed by a set of parentheses. Next, you write the body of the class, enclosed in curly braces. The expression
creates an object that is an instance of a class that either extends the specified superclass or implements the specified interface. A reference to the object returned. (Notice that you do not use the extends or implements keywords in the expression.)
The instance that has been created may be used as a method argument or assigned to a variable.
Java Anonymous Class Example
class outer
{
private double i = 11.5 ;
private static String str = "Hi Java World";
public void display()
{
// Anonymous class
Object Obj=new Object()
{
public String toString()
{ return("Anonymous Class");}
};
System.out.println("i = " + i);
System.out.println("str = " + str);
System.out.println(Obj.toString());
}
}
class AnonymousClass
{
public static void main(String[] arga)
{
outer outobj = new outer(); //create instance of outer class
outobj.display();
}
}
Explanation: When this program compiled, there classes AnonymousClass.class, Outer.class and Outer$1.class are created. These numbers incremented for each anonymous class created by the compiler.
In this program,
new Object() {}
Declares and instantiates an anonymous class. The new keyword followed by the name of the class that specifies the type of object created from an anonymous class. It is followed by empty parentheses, which indicates no argument passed to the constructor of an anonymous class. The code of the class then follows it. An assignment statement can use an anonymous class as shown in the example. In that case, an anonymous class body is followed by a semicolon that marks the end of the assignment statement. The semicolon is part of an assignment statement, not the anonymous class. The following points should be kept in mind while working with anonymous inner classes.
The following points should be kept in mind while working with anonymous inner classes.
• Anonymous inner class cannot have explicit constructors because they have no name to give to the constructor.
• It cannot be public, protected, private or static.
• It cannot either extend a class or implement an interface.
• The anonymous inner class type must be either a subclass of the named type or implementation of the named interface.
• It cannot access static fields, methods or classes (with an exception that constant fields can be declared both static and final).
• It should use when only one instance of the class is needed, and the body of the class is concise.
• It is not a member of any enclosing classes. Rather than being declared along with other members, it is both declared and instantiated where an expression is legal, they must be kept short or fewer or readability will suffer.
• An anonymous class instance is occur in a non-static context.
• You can declare an anonymous class to implement only one interfaces at a time.
• The Clients of an anonymous class invoke only members that it inherits from its super class.
• An anonymous inner class must implement an interface or extend a superclass, but it cannot have an explicit extends or implements clause.
• An anonymous class must always implement all the abstract methods in the superclass or in the interface.
There are three types of anonymous inner class
• Anonymous inner class that extends Class.
• Anonymous inner class that implements interface.
• Anonymous inner class that defined inside method argument.
Difference between Anonymous class and Anonymous Inner class:
• In java, the typical class can extend a class and implement any number of interface simultaneously.
• In java, standard class, we can write any number of constructors.
Anonymous Classes
• In Java, we all encounter situations where we need to create an object but does not need to bother giving it an explicit name.
• With the inner classes, you can create and instantiate a class without bothering to give it a name. It is called an anonymous class.
• This unnamed get rid of additional named objects and makes the code more readable.
Anonymous Inner Classes:
• Anonymous inner classes don’t have a name, and their type must be either a extend another class or implement an interface.
• An anonymous inner class always created as part of a statement; don’t forget to enclose the statement with a curly brace.
• Anonymous inner class are the local inner classes that declared, defined, and automatically instantiated as part of a method invocation.
• In anonymous Inner class, we can’t write any constructor.
Local Inner Classes in Java Example
A local inner class or simply a local class is an inner class that is declared inside a method or constructor or initialization block of the enclosing class. Like regular inner classes, the local classes are associated with a containing instance and can access any member, including the private members of the enclosing class. In addition, it can also access local variables in the method and parameters passed to the method only if the variables are declared final. Just like local variables, the inner class cannot be accessed outside the code block. It is useful when a computation in a method requires the use of specialized class that is not used elsewhere.
The following program shows the use of local variable
class Outer
{
private double i = 11.5 ;
private static String str = "Hi Dinesh Thakur";
public void display()
{
class inner
{
public void outerInfo()
{
System.out.println("i = " + i);
System.out.println("str = " + str);
}
}
inner innObj = new inner();
innObj.outerInfo();
}
}
class LocalClass
{
public static void main(String[] args)
{
Outer outobj = new Outer(); //create instance of outer class
outobj.display();
}
}
Regular Inner Class Example in Java
A regular inner class is a nested class that only exists within an instance of enclosing class. In other words, you cannot instantiate an object of an inner class without first having an object of the outer class. An inner class can use all the methods and fields of the outer class even the private ones directly. The methods and fields of outer class are used as if they were part of the inner class.
The following program demonstrates the concept of inner class
class outer
{
private double i = 11.5 ;
private static String str = "Hi Dinesh";
class inner
{
int j ;
public void display()
{
j = 5;
System.out.println("j = " + j);
System.out.println("j = " + i);
System.out.println("str = " + str);
}
}
}
class InnerClass
{
public static void main(String[] args)
{
outer outobj = new outer(); //create instance of enclsing class
outer.inner innobj = outobj.new inner(); // create intansce of
//regular inner class
innobj.display();
}
}
Multiple Inheritance in Java with Example
Multiple inheritance Occurs when a subclass has more than one superclass, whereby it inherits features from all superclasses. Some OOP languages support this, but Java does not. Java only supports single inheritance. The use of multiple inheritances makes the programming language for more complex to use, learn and implement. The designers of Java wanted to make the language simpler and free from any complication and ambiguity. So the Java designers decided they could do without it. But while working with programs in Java, we often come across situations where we want multiple inheritances. [Read more…] about Multiple Inheritance in Java with Example
Extending Interfaces in Java Examples
When one interface inherits from another interface, that sub-interface inherits all the methods and constants that its super interface declared. In addition, it can also declare new abstract methods and constants. To extend an interface, you use the extends keyword just as you do in the class definition. Unlike a subclass which can directly extend only one subclass, an interface can directly extend multiple interfaces. This can be done using the following syntax
[public] interface InterfaceName
extends interfacel[, interface2, , interfaceN]
{//interface body}
Here, the name of the interface is InterfaceName. The extends clause declares that this interface extends one or more interfaces. These are known as super interfaces and are listed by name. Each super interface name is separated by commas.
Now let us consider a program that demonstrates how interface extends another interface
interface Interface1
{
public void f1();
}
//Interface2 extending Interface1
interface Interface2 extends Interface1
{
public void f2();
}
class x implements Interface2
{
//definition of method declared in interfacel
public void f1()
{
System.out.println("Contents of Method f1() in Interface1");
}
public void f2()
{
System.out.println("Contents of Method f2() in Interface2");
}
public void f3()
{
System.out.println("Contents of Method f3() of Class X");
}
}
class ExtendingInterface
{
public static void main(String[] args)
{
Interface2 v2; //Reference variable of Interface2
v2 = new x(); //assign object of class x
v2.f1();
v2.f2();
x xl=new x();
xl.f3();
}
}
Multiple Interfaces in Java with Example
A class can implement more than one interface. For this, you write the names of all interfaces that the class implement separated by commas following the implements keyword and the class body must provide implementations for all of the methods specified in the interfaces. The syntax for implementing multiple interfaces is
[public] class className [ extends superClassName]
implements interfacel, interface2, interfaceN
{
// Provide implementation for methods of
// all included interfaces .
In order to understand this let us consider an Example.
interface Interface1
{
void f1();
}
//Interface two
interface Interface2
{
void f2();
}
class X implements Interface1,Interface2
{
//definition of method declared in interfacel
public void f1()
{
System.out.println("Contens of Method f1()in Interface1");
}
// definition of method declared in interface2
public void f2()
{
System.out.println("Contens of Method f2()in Interface2") ;
}
public void f3()
{
System.out.println("Contens of Method f3() of Class X");
}
}
class MultipleInterface
{
public static void main(String[] args)
{
Interface1 vl ; //Reference variable of Interfacel
vl = new X(); //assign object of class x
vl.f1();
Interface2 v2; //Reference variable of Interface2
v2 = new X(); //assign object of class x
v2.f2();
X xl=new X();
xl.f3();
}
}
Use of Interface in Java with Example
An interface is just defined like a class but a keyword interface is used instead of the keyword class. It can contain either constants (final fields) or abstract method declarations or both.
All the methods in an interface are public and abstract by default and all the fields are public, static and final by default. Its syntax is .
[public] interface InterfaceName
{
// constant variable declarations
// abstract method declarations
}
The optional public access specifier specifies whether this interface can be used by other classes and packages or not. If public access specifier is omitted, only the classes within its package can use the interface. The keyword interface indicates that an interface named InterfaceName is being defined. The rules for naming the interface are the same as that of valid Java identifiers.
For example, in order to define the Shape interface, we write
interface Shape
{
double area();
double circumference();
}
The complete Example is as shown below
interface Shape
{
double area(); // area method declaration
double circumference(); // circumference method declaration
}
class Rectangle implements Shape
{
private double length,breadth; //Instance data
public Rectangle(double l, double b)
{
length = l;
breadth = b;
}
public double area() { return length*breadth;} //Implementations of
//abstract methods
public double circumference() { return 2*(length+breadth);}
}
class Circle implements Shape
{
public static final double pI = 3.142;
private double radius;
public Circle (double r) { radius = r;}
public double area() {return pI*radius ; }//Implementations of
// abstrct methods
public double circumference() {return 2*pI*radius; }
}
class UseofInterface
{
public static void main(String[] args)
{
Shape[] s =new Shape[2]; //Create an array to hold shapes
s[0] = new Rectangle(10,20);//asssign rectangle object
s[1] = new Circle(3); //assign circle object
double total_area = 0;
for(int i = 0; i<s.length; i++)
{
System.out.println("Area = " +s[i].area()); // Compute area of shapes
//Compute circumference of shape
System.out.println("Circumference = " +s[i].circumference());
}
}
}
Final Method in Java with Example
Sometimes you may want to prevent a subclass from overriding a method in your class. To do this, simply add the keyword final at the start of the method declaration in a superclass. Any attempt to override a final method will result in a compiler error.
class base
{
final void display()
{
System.out.println("Base method called");
}
}
class Derived extends Base
{
void display() //cannot override
{
System.out.println("Base method called");
}
}
class finalMethod
{
public static void main(String[] args)
{
Derived d =new Derived();
d.display();
}
}
On compiling the above example, it will display an error
The following points should be remembered while using final methods.
• Private methods of the superclass are automatically considered to be final. This is because you cannot override a method in the subclass. Similarly, the static methods are also implicitly final as they cannot be overridden either.
• Since the compiler knows that final methods cannot be overridden by a subclass, so these methods can sometimes provide performance enhancement by removing calls to final methods and replacing them with the expanded code of their declarations at each method call location. This technique of replacing code is known as inlining the code. There is no transfer of control between the calling and the called method that result in removing the method call overhead which in turn improves the execution time.
Methods made inline should be small and contain only few lines of code. If it grows in size, the execution time benefits become a very costly affair.
• A final’s method declaration can never change, so all subclasses use the same method implementation and call to one can be resolved at compile time. This is known as static binding.
Abstract Methods and Classes in Java Example
An abstract method is a method prototype (i.e. return type, method name, list of parameters and optionally throws clause) without any implementation. Its implementation is provided by the subclass(es) of the class in which it is declared. To create an abstract method, simply specify the modifier abstract followed by the method declaration and replace the method body by a semicolon. For example, The abstract method area () of the Shape superclass will be written as
abstract double area();
The class that contains atleast one abstract method must be declared abstract. Such a class is known as an abstract class. A class is made abstract by putting the keyword abstract in front of class keyword in the first line of class definition. For example: The Shape superclass that contains abstract method area () will now look like,
abstract class Shape
{
abstract double area() ;//abstract method
abstract double circumference();
}
Abstract classes are like normal classes with fields and methods but you cannot create objects of abstract classes using the new operator. However, you can declare a variable of an abstract class type. Such variables are used to manipulate subclass objects polymorphically. In other words, such variable can be used to refer to an instance of any of the subclasses of abstract superclass.
For example: If you try to instantiate an object of the abstract superclass Shape using the following statement,
Shape s = new Shape(3,4); // error, Shape abstract
It will result in compile time error. Moreover, it makes no sense to create Shape object. What dimensions would it have? What would be its area?
Abstract classes are useful when you want to create a generic type that is used as a superclass for two or more subclasses, but the superclass itself does not represent an actual object. For example: As in case of Shape class which we need for inheritance and polymorphism but want only to instantiate objects of its subclasses, not Shape itself.
The following example demonstrates the use of abstract class.
abstract class Shape
{
abstract void area() ;
abstract void circumference();
}
class Rectangle extends Shape
{
private double length,breadth;
Rectangle(double x,double y)
{
length = x ;
breadth = y;
}
public void area()
{
System.out.println("Area of Rectangle is : " + (length*breadth));
}
public void circumference()
{
System.out.println("Circumference of Rectangle is : "+2*(length+breadth));
}
}
class Circle extends Shape
{
private double radius;
Circle(double r)
{
radius = r ;
}
public void area()
{
System.out.println("Area of Circle is : "+( Math.PI*radius*radius));
}
public void circumference()
{
System.out.println("Circumference of Circle is : "+ 2*Math.PI*radius);
}
}
class AbstractMethodsClasses
{
public static void main(String[] args)
{
Shape s; //Shape class reference variable
Rectangle r= new Rectangle(10,20);
s = r; //Assign rectangle reference to shape reference
s.area() ;
s.circumference() ;
Circle c = new Circle(5);
s = c; //Assign circle reference to shape reference
s.area();
s.circumference();
}
}
instanceof Operator in Java Example
Sometimes it is useful to know the type of the object at runtime. For example, if you try to make a cast that is invalid, an exception will be thrown. You can overcome this problem if you are able to verify that the object is of the type you expect before you make the cast. This is possible using the instanceof operator. The general from of instanceof operator is objRef instanceof type
Here, objRef is a reference to an instance of a class and type is a class type. The instanceof operator returns true if the objRef is of the same type as the right operand or can be cast into any of the subclass type, otherwise it returns false.
Consider the same Shape hierarchy as discussed in previous section and we want to check whether reference variable s contains an object of type Rectangle then it will be written as
if(s instanceof Rectangle)
System.out.println (“Contains reference to Rectangle object”);
else
System.out.println (“Contains reference to other object”);
class Shape
{
public void area ()
{
System.out.println("Base class area method is called");
}
}
class Rectangle extends Shape
{
private double length,breadth;
Rectangle(double x,double y)
{
length = x ;
breadth = y ;
}
public void area()
{
System.out.println("Area of Rectangle is = " + (length * breadth));
}
}
class Circle extends Shape
{
private double radius;
Circle(double r)
{
radius = r ;
}
public void area()
{
System.out.println("Area of Circle is = " + (Math.PI*radius*radius));
}
}
class InstanceofOperator
{
public static void main(String[] args)
{
Shape s; //Shape class reference variable
Rectangle r = new Rectangle(10,20);
s = r; //Assign rectangle reference to shape reference
if (s instanceof Rectangle)
System.out.println("Contain Reference to Rectangle Object");
else
System.out.println("Contain Reference to some other Object");
}
}
Casting Objects in Java Example
You can cast an object to another class type provided a class is a subclass of other i.e. casting takes place within an inheritance hierarchy, so that the source and destination are within the same hierarchy.
If s be a reference variable of type Shape and rect be a reference variable that holds object of type Rectangle. We can assign the Rectangle reference rect to the Shape reference variable s. This is accomplished using the following statements,
Shape s;
Rectangle rect = new Rectangle (10,20) ;
$ = rect;
In the last statement, the compiler implicitly casts a Rectangle type to a Shape type. This
is possible because as Rectangle is derived from Shape so each Rectangle object is an object of Shape class. Such type of casting in which an object implicitly casts to a superclass type is known as casting up through the class hierarchy.
Now let us consider the following statement in which we are attempting to implicit downcast a Shape type to a Rectangle.
rect = s ;
This is invalid statement and compiler will generate an error on compilation. This is because not all the instances of Shape are also instances of Rectangle. So if you want to make this statement work, you must cast it explicitly. For this, like with primitive types, enclose the class type that an object is being cast to (in our case Rectangle) in parentheses in front of the object reference s. So, the valid statement is
rect = (Rectangle)s;
Such type of casting in which an object explicitly casts to a subclass is known as casting down through the class hierarchy. For the casting to be successful, make sure that the object to be cast is an instance of subclass.
You will need to cast an object to a subclass type when you need to access a method that is unique to a subclass. For example, suppose the Rectangle class contains a method getLength () which returns the length of the rectangle. Since this method does not belong to Shape class and therefore cannot be invoked through a reference variable s of type Shape even though it references a Rectangle object. It must be invoked through a reference of type “Rectangle like recto So if you want to invoke a method getlength () , you must explicitly cast reference variable s to type
Rectangle using the following statement.
((Rectangle) s) .getLength (); .
In this statement, the object pointed to by s is first cast to type Rectangle and the result of cast is then used to invoke the method getLength () . If the method was not bf type Rectangle, the cast would, cause an exception to be thrown. For example
The statement,.
((Circle) s). getLength () ;
will throw an exception java.lang. ClassCastException as s ‘currently holds the Rectangle object.
class Shape
{
public void area()
{
System.out.println("Base class area mathod is called");
}
}
class Rectangle extends Shape
{
double length,breadth;
Rectangle(double x,double y)
{
length = x ;
breadth = y ;
}
public double getLength() { return length;}
public double getBreadth() { return breadth;}
public void area()
{
System.out.println("Area of Rectangle is = "+ (length * breadth));
}
}
class Circle extends Shape
{
private double radius;
Circle(double r)
{
radius = r ;
}
public double getRadius() { return radius;}
public void area()
{
System.out.println("Area of Circle is = " +(Math.PI*radius*radius));
}
}
class CastingObject
{
public static void main(String[] args)
{
Shape s; //Shape class reference variable
Rectangle r = new Rectangle(10,20);
s = r; //Assign rectangle reference to shape reference
System.out.println("Length = "+((Rectangle)s).getLength());
System.out.println("Breadth = "+((Rectangle)s).getBreadth());
s.area();
Circle c = new Circle(5) ;
s = c; //Assign circle reference to shape reference
System.out.println("Radius = "+((Circle)s).getRadius());
s.area();
}
}
Referencing Subclass Object Using Superclass Reference Variable
As we know that in order to declare a variable that references an object, we use the following
syntax.
ClassName variableName;
Here, variableName is the name of the reference variable and ClassName is the name of its class. Thus, variablename can reference any object of class ClassName. However, it can also reference any object whose class is a subclass of ClassName. For example: If a class A is a superclass of class B and class B is a superclass of class C then in that case, variable of class A can reference any object derived from that class (i.e. object of class B and class c). This is possible because each subclass object is an object of its superclass but not vice versa.
To illustrate how a superclass reference variable can refer the derive class object, let us consider the following example in which the class Dervl and Derv2 are derived from common superclass Base. All these classes have methods with the same name and we are accessing these methods using superclass reference variable.
class Base
{
public void display()
{
System.out.println("Base class display method is called");
}
}
class Derv1 extends Base
{
public void display()
{
System.out.println("Derv1 class display method is called");
}
}
class derv2 extends Base
{
public void display()
{
System.out.println("Derv2 class display method is called");
}
}
class polymorhism
{
public static void main(String[] args)
{
Base ptr; //Bae class reference variable
Derv1 dl = new Derv1();
Derv1 d2 = new Derv1();
ptr = dl; // ptr contain reference of Derv1 object
ptr.display();
ptr = d2; // ptr contain reference of derv2 object
ptr.display();
}
}
The output of the program reveals that the method display () of the subclasses are invoked. If the reference variable of the superclass Base contains a reference to Derv1 object, the display () method for that object will be called. Similarly, if the reference variable ptr contains a reference to Derv2 object, the () method for that object will be called. This means that one method call,
ptr().display;
can call different methods depending on the momentary contents of ptr:. This is how polymorphism is achieved. Notice that which overridden method will called is always determined by the type of the object referenced by the variable, not the type of the object reference variable. This task of determining which implementation of method will be used is performed by the JVM dynamically at run time. This is known as dynamic binding.
The polymorphic behavior can only be achieved if the following requirements are fulfilled.
• The method call for a subclass object must be through a superclass reference variable.
• The method called .must be declared in the superclass and defined in the subclass.
• The method in the superclass and subclass must have the same name and parameter list with the same number of parameters where corresponding parameters must be of the same type.
• The method return type must either be the same in the superclass and subclasses or must be covariant. Return types are said to be covariant if the return type of the method in the derived class is a subclass of the return type of the base class.
• The method access specifier must be no more restrictive in the subclass than in the superclass.
Visibility increases and Restriction decreases
private, none (if modifier used), protected, public
Now let us consider a practical example to understand the importance of polymorphism.
Consider Rectangle and Circle be the subclasses of class Shape. Suppose we want to calculate area of any shape so we will define an area () method in the Shape class and override it in the Rectangle and Circle subclass to calculate area of rectangle and circle.
class Shape
{
public void area()
{
System.out.println("Base class area method is called");
}
}
class Rectangle extends Shape
{
private double length,breadth;
Rectangle(double x,double y)
{
length = x ;
breadth = y ;
}
public void area ()
{
System.out.println("Area of Rectangle is = " + (length * breadth));
}
}
class Circle extends Shape
{
private double radius;
Circle(double r)
{
radius = r ;
}
public void area()
{
System.out.println("Area of Circle is = " + (Math.PI*radius));
}
}
class ShapeEx
{
public static void main(String[] args)
{
Shape s; //Shape class reference variable
Rectangle r = new Rectangle(10,20);
s = r; //Assingn rectangle reference to shape reference
s.area();
Circle c = new Circle(5);
s = c; //Assign circle reference to shape reference
s.area();
}
}