Association is nothing more than a connection that exists between two classes. We use the objects of these classes to set up the connection. Association can be done in three ways one-to-one, one-to-many and many-to-many. Let’s have a look at an example showing how association is implemented in Java. [Read more…] about Association, Composition and Aggregation in Java
What is Abstraction in Java? Abstract Class or Interface
Abstraction in Java: The words “data abstraction” and “information hiding” are generally used interchangeably. The two terms mean the same thing in this context. Abstraction is a simple representation of a complicated situation. It is a technique where we hide irrelevant details and represent only the essential aspects of a context so that one can focus on features one is interested; It helps to deal a complex system by concentrating on the essential features only. It is designed to make it easier to maintain, read and work on the code. In the object-oriented model, a class is an abstraction of existing entities in the domain of the software system. Ex: A car viewed as a car rather than its components. [Read more…] about What is Abstraction in Java? Abstract Class or Interface
Example of Multilevel Inheritance in Java
Function Overloading and Method Overloading in Java
When in a class, we have more then one method with similar name but with different type signatures i.e. with different number of parameters or with different types of parameters, then we say that the method is overloaded. Compiler will recognize which method to execute on the basis of the type and number of parameters used while calling the method.
class Rectangle
{
int length,breath,a;
void getData(int x,int y)
{
length=x;
breath=y;
}
void getData(int x)
{
length=x;
breath=15;
}
void getData()
{
length=60;
breath=15;
}
int getArea()
{
a=length*breath;
return(a);
}
}
class FunctionMethod
{
public static void main(String args[])
{
Rectangle Rect = new Rectangle();
Rectangle Rect1 = new Rectangle();
Rectangle Rect2 = new Rectangle();
Rect.getData();
Rect1.getData(30);
Rect2.getData(40,60);
System.out.println("Area of First Rectangle is : "+Rect.getArea());
System.out.println("Area of Second Rectangle is : "+Rect1.getArea());
System.out.println("Area of Third Rectangle is : "+Rect2.getArea());
}
}
Java Example for Method Overloading
Example of Method Overloading in Java
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it certainly refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
class WorkerDetail
{
int c,s;
String n;
float h;
void SetSalary(int x, String y, int z)
{
c=x;
n=y;
s=x;
}
void ShowDetail()
{
System.out.println("Code : "+ c);
System.out.println("Name : "+n);
System.out.println("Salary : "+s);
}
void getHra()
{
h=(float)s*60/100;
System.out.println("HRA : "+h);
}
}
class officerDetail extends WorkerDetail
{
float h,g;
void getHra()
{
h=(float)s*75/100;
System.out.println("HRA : "+h);
}
void getGross()
{
g=s+h;
System.out.println("Gross : "+g);
}
};
class ExMethodOverloading
{
public static void main(String args[])
{
WorkerDetail wD = new WorkerDetail();
officerDetail oD = new officerDetail();
wD.SetSalary(121,"Aman",13000);
oD.SetSalary(111,"Amrik",30000);
System.out.println("Detail of Worker is :");
wD.ShowDetail();
wD.getHra();
System.out.println("Detail of Officer is :");
oD.ShowDetail();
oD.getHra();
oD.getGross();
}
};
Example of Inheritance in Java
Calculate Area of Rectangle and Triangle using Single Inheritance
Single Inheritance in Java Example
Inheritance is one the most powerful concepts in an object-oriented language. Through inheritance the code developed for one class can be used in another class. That is, the data members made in a class can be used in another class. Inheritance is done by creating new classes that are extensions of other classes. The new class is known as a subclass. The original class is known as a superclass. The subclass has all the attributes of the superclass, and in addition has attributes that it defines itself. A class can have only one superclass. This is known as single inheritance. A superclass can have multiple subclasses.
Declaring Inheritance
A class inherits a super class with the help of keyword: extends
Syntax :
class classname extends anotherclass
{
… body of class
}
The extends keyword immediately follows the class name. It is followed by the name of the superclass from which this class will inherit characteristics. There can be only one class name following the extends keyword. Hence, inheritance provides a powerful mechanism for reusing existing code.
class Rectangle
{
int l,b;
void Setval(int x,int y)
{
l=x;
b=y;
}
int GetRect()
{
return l*b;
}
}
class Triangle extends Rectangle
{
int b,h;
float a;
void SetData(int v,int u)
{
b=u;
h=v;
}
float GetTri()
{
a=(float)l/2*b*h;
return (a);
}
}
class SingleInheritance
{
public static void main(String args[])
{
Triangle Tri=new Triangle();
Tri.Setval(50,8);
Tri.SetData(17,7);
System.out.println("Area of Rectangle is :" +Tri.GetRect());
System.out.println("Area of Triangle is :"+Tri.GetTri());
}
}
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();
}
}
Object Class in Java Example
All the classes in Java that you have defined so far are subclasses by default whether or not you have specified the superclass. The class which all classes in Java are descendent of (directly or indirectly) is java.lang.Object class. So each class inherits the instance methods of Object class. It is important to be familiar with the methods provided by the Object class so that you can use them in your class.
Using Object class methods
There are methods in Object class:
Public String toString (): This method returns a string representation of an object. The default implementation returns the name of the class followed by ‘@’ and the hexadecimal representation for the object. You can override this method in your classes, to return your String object for your class.
// Returns a string that lists the host name.
// @, Returns a hexadecimal representation for the object.
public String toString(){
return getClass().getName()+‘@’+Integer.toHexString(dataSource.hashCode());
}
It is always recommended to override toString() method,returns the desired String representation of Object. So, override of toString() method refer – Overriding toString() in Java
Note : If you print any Object reference, then internally invokes toString() method.
Teacher t = new Teacher();
// Below two statements are equivalent
System.out.println(t);
System.out.println(t.toString());
public boolean equals (Object obj): It compares two objects for equality and returns true if they are equal and false otherwise. The comparison is case-sensitive. The code below is the equals() method in the Object class. The method is checking whether the current instance is the same as the previously passed Object.
public boolean equals(Object obj) {
return(this== obj);
}
public final class getClass(): This method returns a class Object (package Java.lang) that is locked by static synchronized methods of the represented class, and that contains information about the object’s type, such as its classname, its superclass and the interfaces it implements. It also is used to get metadata of this class.
public class clObject {
public static void main(String[] args) {
Object obj = new String(“ecomputernotes”);
Class cl = obj.getClass();
System.out.println(“The returned Class object is the : “ + c.getName());
}
}
NOTE: The getclass() methods of the Object class declared final since their implementation are essential for proper behavior of an object, and so those methods cannot be overridden by any class.
Public int hashcode (): A hash table is a storage mechanism that creates a key-and-value pair for each element. For example, suppose you are keeping records of employees within a company. You need to develop a mechanism for retrieving these records based on employees’ social security numbers. An array really won’t work well for this because the nine-digit identification number is too large. (Vectors and arrays work best for an ordered list of sequential values.) In this situation, hash tables are the answer.
Hash tables enable quick location and retrieval of data by using a key. This key is associated with data contained within an object. The key and value can be from any object, but the key object must implement the hashCode() and equals() methods. Once these methods have implemented, the hash table computes a small integer from the key; this is the hash code and the location where the key/value pair exists. Unlike arrays and vectors, the order of values in a hash table is not important-the hash code ID is all that matters. What is important is that the keys are unique: Only one value can store for each key. If you add a value to a key that is already holding another value, then the added value replace the preexisting value.
As with other data structures, the hash table’s performance is affected by the ratio between the number of elements and the capacity of the structure. This ratio is called the load factor and represented as a percentage. Hash tables need to allocate more storage space than is needed because they generate the unique hash code from the identifying key. As the load factor increases,
so does the likelihood that two or more generated hash codes have the same value; this is called a collision. The extra space is used to ensure that all key/value pairs remain unique. Ideally, the load factor is not higher than 50%; that is, the capacity should be double the number of elements contained in the hash table. If the load factor goes over 75%, the hash table automatically doubles the capacity to ensure adequate performance.
Protected Object clone() throws CloneNotSupportedException: This method creates a copy of the object on which it is called.
Protected void finalize() throws Throwable: The finalize method is a particular method, declared in the object class which allows cleaning up of objects which are not in use (not referenced).
When any objects no longer reference an object, Java reclaims the memory space using garbage collection. Java calls a finalize method before garbage collection takes place.
Syntax:
void finalize() {
…..body of finalize method
}
Finalize methods always have a return type of void and override a default destructor in java.object.Object.
A program can call finalize directly just as it would any other method. However, calling finalize not initiate any garbage collection. It treated like any other method called directly. When Java does garbage collection, finalize is still called even if it has already been called directly by the program.
The finalize method can be overloaded also. If Java finds a finalize method with arguments at garbage-collection time, it looks for a finalize method with no arguments. If it does not find one, Java uses the default finalize method instead.
The system only calls finalize when it is ready to reclaim the memory associated with the object and not immediately after an object no longer referenced. That is, finalize() is called only when the system is running short of memory so that it may be called long after the application finishes.
Object Class in Java Example
class Rectangle extends Object
{
private double length,breadth;
Rectangle(double x,double y)
{
length = x ;
breadth = y ;
}
public void area()
{
System.out.println("Area of Rectangle is = " + breadth);
}
public void circumference()
{
System.out.println("Circumferen of Rectangle is= "+2*(length+breadth));
}
}
class ObjectClass
{
public static void main(String[] args)
{
Rectangle r = new Rectangle(10,20);
Rectangle rl = new Rectangle(10,20);
System.out.println("String Representation = " + r.toString());
System.out.println("Class Name = " + r.getClass());
System.out.println("Hash Code = " + r.hashCode());
System.out.println("r.rquals(rl) = " + r.equals(rl));
}
}
Composition in Java Example
Inheritance is suitable only when classes are in a relationship in which subclass is a (kind of) superclass. For example: A Car is a Vehicle so the class Car has all the features of class Vehicle in addition to the features of its own class. However, we cannot always have. is a relationship between objects of different classes. For example: A car is not a kind of engine. To represent such a relationship, we have an alternative to inheritance known as composition. It is applied when classes are in a relationship in which subclass has a (part of) superclass.
Unlike inheritance in which a subclass extends the functionality of a superclass, in composition, a class reuses the functionality simply by creating a reference to the object of the class it wants to reuse. For example: A car has an engine, a window has a button, a zoo has a tiger.
Now consider. the following program that demonstrates the concept of composition
class Date
{
private int day;
private int month;
private int year;
Date(int dd, int mm,int yy)
{
System.out.println("Constructor of Data Class is Called");
day=dd;
month=mm;
year=yy;
}
public String toString()
{
return (day+"/"+month+"/"+year);
}
}
class Employee
{
private int id;
private String name;
private Date hireDate; //object of Data class
Employee(int num,String n, Date hire)
{
System.out.println("Constructor of Employee Class is Called");
id=num ;
name=n ;
hireDate=hire;
}
public void display()
{
System.out.println("id = "+id);
System.out.println("Name = "+name);
System.out.println("Hiredate = "+hireDate);
}
}
public class Composition
{
public static void main(String[] args)
{
Date d = new Date(01,01,2011);
Employee emp = new Employee(1,"Dinesh Thakur",d);
emp.display();
}
}
In this example, we first define a class Date for maintaining the date information. Then we define a class Employee that not only contains members id, name and display () but also contains a reference variable hireDate to refer objects of class Date as its member, which maintains employee’s hiredate.
The statement,
emp.display () ;
on execution will display employee’s id, name and the hiredate. The hireDate is obtained with an implicit call to the Date class’s toString () method.
Multilevel Inheritance in Java Example
In Our Example illustrates Multilevel Inheritance, Here Class B is derived from superclass A which itself acts as a superclass for the subclass C. The class C inherits the members of Class B directly as it is explicitly derived from it, whereas the members of class A are inherited indirectly into class c (via class B). So the class B acts as a direct superclass and A acts as a indirect superclass for class C.
Each parent-child relationship is representing a level. So class A-class B relationship represents the first level of inheritance and class B-c1ass C represents second level of Inheritance. As the above class hierarchy contains two levels of inheritance which thus represents multilevel inheritance. In multilevel inheritance, there is no limit to the number of levels in a class hierarchy.
Now let us consider a program that shows the multi-level inheritance
class person
{
private String name;
person(String s)
{
setName(s);
}
public void setName(String s)
{
name = s;
}
public String getName()
{
return name;
}
public void display()
{
System.out.println("Name = " + name);
}
}
class Employee extends person
{
private int empid;
Employee(String sname,int id) //Constructor Method
{
super(sname);
setEmpid(id);
}
public void setEmpid(int id)
{
empid = id;
}
public int getEmpid()
{
return empid;
}
public void display()
{
super.display();
System.out.println("Empid = " + empid);
}
};
class HourlyEmployee extends Employee
{
private double hourlyRate;
private int hoursWorked;
HourlyEmployee(String sname,int id,double hr,int hw)
{
super(sname,id);
hourlyRate = hr;
hoursWorked = hw;
}
public double GetGrosspay()
{
return (hourlyRate * hoursWorked);
}
public void display()
{
super.display();
System.out.println("Hourly Rate = " + hourlyRate);
System.out.println("Hours Worked = " + hoursWorked);
System.out.println("Gross pay = " + GetGrosspay());
}
};
class MultilevelInheritance
{
public static void main(String[] args)
{
HourlyEmployee emp = new HourlyEmployee("Dinesh Thakur",1,15,1800);
emp.display();
}
}
Method Overriding in Java with Examples
In a class hierarchy, A subclass can contain a method with the same signature and return type as in its superclass, then the method in the subclass is said to override the method in the superclass. However in certain situations, the subclass need to modify the implementation (code) of a method defined in the superclass without changing the parameter list. This is achieved by overriding or redefining the method in the subclass. [Read more…] about Method Overriding in Java with Examples
Super Keyword in Java Example
The super() keyword is used to reference objects for the immediate parent class. A subclass inherits the accessible data fields and methods from its superclass, but the constructors of the superclass are not inherited in the subclass. They can only be invoked from constructors of the subclass( es) using the keyword super. [Read more…] about Super Keyword in Java Example
Inheritance Protected Members Java Example
A protected field or method in a public class can be accessed directly by all classes within the same package and its subclasses even if the subclasses are in different packages. It is more restrictive than default (or package) access.
class Num //super class
{
protected int x,y; //protected Members
Num(int a, int b)
{
x=a;
y=b;
}
public void showxY()
{
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
class Result extends Num
{
private int z ;
Result(int a,int b)
{
super(a,b);
}
public void add()
{
z = x+y;
}
public void show()
{
System.out.println("z = " + z);
}
}
public class ProtectedInheritance
{
public static void main(String[] args)
{
Result d = new Result(5,6);
d.showxY();
d.add();
d.show();
}
}
In the above program, we create a superclass Num having protected fields x and y and a method showXY (). Then we derive a/subclass Result ,from Num which contains its own data field z and two methods add () and showZ(). The data fields x and y of superclass Num are declared as protected because we want that the method add () of the subclass can access it directly. In main () , we instantiate the object of subclass Result and initialize the fields x and y of superclass Num with values 5 and 6 respectively using a call to the constructor. Then the method add () is called, to calculate the sum of x and y and display the result using showZ() method.
Private Inheritance in Java Example
Inheritance is a mechanism of creating a new class from an existing class by inheriting the features of existing class and adding additional features of its own. When a class is derived from an existing class, all the members of the superclass are automatically inherited in the subclass. However, it is also possible to restrict access to fields and method of the superclass in the subclass. This is possible by applying the access Specifiers to the member of the superclass. If you do not want a subclass to access a superclass member, give that member private access. The private members of the superclass remain private (accessible within the superclass only) in the superclass and hence are not accessible directly to the members of the subclass. However, the subclass can access them indirectly through the inherited accessible methods of the superclass.
class Base
{
private int numl;//private member
public void setData(int n)
{
numl = n;//private member accessed within the class
}
public int getData()
{
return numl;//private member accessed within the class
}
}
class Derived extends Base
{
int num2 ;
public void product()
{
int num =getData();
System.out.println("product = " + (num2 * num));
}
}
public class PrivateInheritance
{
public static void main(String[] args)
{
Derived d = new Derived();
d.setData(20) ; //to set private member numl
d.num2 = 10 ;
d.product();
}
}
In the above program, numl is a private data field defined in the class Base. Only the methods setData () and getData () in the class Base can access this field directly by name from within its definition. However, it is not accessible to any other class including the Derived subclass.
In order to access the private field numl of the superclass Base in the method product () of the subclass Derived, we call the getData () method of the class Base as shown in the statement