Java Abstract Class
Java Abstract Class
The abstract class in Java cannot be instantiated (we cannot create objects of
abstract classes). We use the abstract keyword to declare an abstract class. For
example,
An abstract class can have both the regular methods and abstract methods. For
example,
A method that doesn't have its body is known as an abstract method. We use the
same abstract keyword to create abstract methods. For example,
abstract void display();
Here, display() is an abstract method. The body of display() is replaced by ;.
If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error. For example,
// error
// class should be abstract
class Language {
// abstract method
abstract void method1();
}
Example: Java Abstract Class and Method
Though abstract classes cannot be instantiated, we can create subclasses from it.
We can then access members of the abstract class using the object of the
subclass. For example,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the
abstract class using the object obj.
If the abstract class includes any abstract method, then all the child classes
inherited from the abstract superclass must provide the implementation of the
abstract method. For example,
class Main {
public static void main(String[] args) {
d1.makeSound();
d1.eat();
}
}
Output
Bark bark
I can eat.
In the above example, we have created an abstract class Animal. The class
contains an abstract method makeSound() and a non-abstract method eat().
We have inherited a subclass Dog from the superclass Animal. Here, the
subclass Dog provides the implementation for the abstract method makeSound().
Note: If the Dog class doesn't provide the implementation of the abstract
method makeSound(), Dog should also be declared as abstract. This is because
the subclass Dog inherits makeSound() from Animal.
An abstract class can have constructors like the regular class. And, we can
access the constructor of an abstract class from the subclass using
the super keyword. For example,
Here, we have used the super() inside the constructor of Dog to access the
constructor of the Animal.
Note that the super should always be the first statement of the subclass
constructor.
Java Abstraction
The major use of abstract classes and methods is to achieve abstraction in Java.
The major advantage of hiding the working of the brake is that now the
manufacturer can implement brake differently for different motorbikes,
however, what brake does will be the same.
class Main {
public static void main(String[] args) {
MountainBike m1 = new MountainBike();
m1.brake();
SportsBike s1 = new SportsBike();
s1.brake();
}
}
Output:
MountainBike Brake
SportsBike Brake
In the above example, we have created an abstract super class MotorBike. The
superclass MotorBike has an abstract method brake().
• We can access the static attributes and methods of an abstract class using
the reference of the abstract class. For example,
Animal.staticMethod();
During inheritance, we must declare methods with the final keyword for which
we are required to follow the same implementation throughout all the derived
classes. Note that it is not necessary to declare final methods in the initial stage
of inheritance(base class always). We can declare a final method in any subclass
for which we want that if any other class extends this subclass, then it must
follow the same implementation of the method as in that subclass.
// Driver class
public class Test
{
public static void main(String[] args)
{
// creating Rectangle object
Shape s1 = new Rectangle(10, 20);
//getting area of s1
System.out.println("area of s1 : "+ s1.getArea());
//getting area of s2
System.out.println("area of s2 : "+ s2.getArea());
}
}
Output:
width of s1 : 10.0
height of s1 : 20.0
width of s2 : 10.0
height of s2 : 10.0
area of s1 : 200.0
area of s2 : 100.0
When a class is declared as final then it cannot be subclassed i.e. no other class
can extend it. This is particularly useful, for example, when creating an
immutable class like the predefined String class. The following fragment
illustrates the final keyword with a class:
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Note :
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Normally, Java resolves calls to methods dynamically, at run time. This is
called late or dynamic binding. However, since final methods cannot be
overridden, a call to one can be resolved at compile time. This is called early or
static binding.
1. toString() method
The toString() provides a String representation of an object and is used to
convert an object to a String. The default toString() method for class Object
returns a string consisting of the name of the class of which the object is an
instance, the at-sign character `@’, and the unsigned hexadecimal representation
of the hash code of the object. In other words, it is defined as:
// Default behavior of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
Note: Whenever we try to print any Object reference, then internally toString()
method is called.
Student s = new Student();
2.hashCode() method
For every object, JVM generates a unique number which is a hashcode. It returns
distinct integers for distinct objects. A common misconception about this method
is that the hashCode() method returns the address of the object, which is not
correct. It converts the internal address of the object to an integer by using an
algorithm. The hashCode() method is native because in Java it is impossible to
find the address of an object, so it uses native languages like C/C++ to find the
address of the object.
// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}
// Overriding hashCode()
@Override public int hashCode() { return roll_no; }
// Driver code
public static void main(String args[])
{
Student s = new Student();
Output :
Student@64
Student@64
Note that 4*160 + 6*161 = 100
4.getClass() method
It returns the class object of “this” object and is used to get the actual runtime
class of the object. It can also be used to get metadata of this class. The returned
Class object is the object that is locked by static synchronized methods of the
represented class. As it is final so we don’t override it.
5. finalize() method
t = null;
System.out.println("end");
}
Output:
1510467688
end
finalize method called
6. clone() method
It returns a new object that is exactly the same as this object. For clone() method
refer Clone().
Output