0% found this document useful (0 votes)
18 views20 pages

Java Abstract Class

The document explains the concept of abstract classes and methods in Java, highlighting that abstract classes cannot be instantiated and must contain abstract methods if they are declared abstract. It also covers the use of the final keyword to restrict inheritance and method overriding, as well as the Object class and its methods, which are fundamental to all Java classes. Key points include the importance of abstraction in managing complexity and the necessity of overriding methods like equals() and hashCode() for custom object comparison.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views20 pages

Java Abstract Class

The document explains the concept of abstract classes and methods in Java, highlighting that abstract classes cannot be instantiated and must contain abstract methods if they are declared abstract. It also covers the use of the final keyword to restrict inheritance and method overriding, as well as the Object class and its methods, which are fundamental to all Java classes. Key points include the importance of abstraction in managing complexity and the necessity of overriding methods like equals() and hashCode() for custom object comparison.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

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,

// create an abstract class


abstract class Language {
// fields and methods
}
...

// try to create an object Language


// throws an error
Language obj = new Language();

An abstract class can have both the regular methods and abstract methods. For
example,

abstract class Language


{
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular method");
}
}
Java Abstract Method

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,

abstract class Language {

// method of abstract class


public void display() {
System.out.println("This is Java Programming");
}
}

class Main extends Language {

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// access method of abstract class


// using object of Main class
obj.display();
}
}
Output
This is Java programming
In the above example, we have created an abstract class named Language. The
class contains a regular method display().
We have created the Main class that inherits the abstract class. Notice the
statement,

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.

Implementing Abstract Methods

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,

abstract class Animal {


abstract void makeSound();

public void eat() {


System.out.println("I can eat.");
}
}

class Dog extends Animal {

// provide implementation of abstract method


public void makeSound() {
System.out.println("Bark bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of Dog class


Dog d1 = new Dog();

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().

We then used the object d1 of the Dog class to call


methods makeSound() and eat().

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.

Accesses Constructor of Abstract Classes

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,

abstract class Animal {


Animal() {
….
}
}

class Dog extends Animal {


Dog() {
super();
...
}
}

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.

Abstraction is an important concept of object-oriented programming that allows


us to hide unnecessary details and only show the needed information.

This allows us to manage complexity by omitting or hiding details with a simpler,


higher-level idea.

A practical example of abstraction can be motorbike brakes. We know what brake


does. When we apply the brake, the motorbike will stop. However, the working
of the brake is kept hidden from us.

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.

Let's take an example that helps us to better understand Java abstraction.

Example 3: Java Abstraction

abstract class MotorBike {


abstract void brake();
}

class SportsBike extends MotorBike {

// implementation of abstract method


public void brake() {
System.out.println("SportsBike Brake");
}
}

class MountainBike extends MotorBike {

// implementation of abstract method


public void brake() {
System.out.println("MountainBike Brake");
}
}

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().

The brake() method cannot be implemented inside MotorBike. It is because


every bike has different implementation of brakes. So, all the subclasses
of MotorBike would have different implementation of brake(). So, the
implementation of brake() in MotorBike is kept hidden.
Here, MountainBike makes its own implementation
of brake() and SportsBike makes its own implementation of brake().
Key Points to Remember

• We use the abstract keyword to create abstract classes and methods.


• An abstract method doesn't have any implementation (method body).
• A class containing abstract methods should also be abstract.

• We cannot create objects of an abstract class.

• To implement features of an abstract class, we inherit subclasses from it


and create objects of the subclass.

• A subclass must override all abstract methods of an abstract class.


However, if the subclass is declared abstract, it's not mandatory to
override abstract methods.

• We can access the static attributes and methods of an abstract class using
the reference of the abstract class. For example,
Animal.staticMethod();

Using final with Inheritance in Java

final is a keyword in java used for restricting some functionalities. We can


declare variables, methods, and classes with the final keyword.

Using final with inheritance

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.

// Java program to illustrate use of final with inheritance


// base class
abstract class Shape
{
private double width;
private double height;
// Shape class parameterized constructor
public Shape(double width, double height)
{
this.width = width;
this.height = height;
}
// getWidth method is declared as final
// so any class extending
// Shape can't override it
public final double getWidth()
{
return width;
}

// getHeight method is declared as final


// so any class extending Shape
// can not override it
public final double getHeight()
{
return height;
}
// method getArea() declared abstract because
// it upon its subclasses to provide
// complete implementation
abstract double getArea();
}
// derived class one
class Rectangle extends Shape
{
// Rectangle class parameterized constructor
public Rectangle(double width, double height)
{
// calling Shape class constructor
super(width, height);
}

// getArea method is overridden and declared


// as final so any class extending
// Rectangle can't override it
@Override
final double getArea()
{
return this.getHeight() * this.getWidth();
}

//derived class two


class Square extends Shape
{
// Square class parameterized constructor
public Square(double side)
{
// calling Shape class constructor
super(side, side);
}

// getArea method is overridden and declared as


// final so any class extending
// Square can't override it
@Override
final double getArea()
{
return this.getHeight() * this.getWidth();
}
}

// Driver class
public class Test
{
public static void main(String[] args)
{
// creating Rectangle object
Shape s1 = new Rectangle(10, 20);

// creating Square object


Shape s2 = new Square(10);

// getting width and height of s1


System.out.println("width of s1 : "+ s1.getWidth());
System.out.println("height of s1 : "+ s1.getHeight());

// getting width and height of s2


System.out.println("width of s2 : "+ s2.getWidth());
System.out.println("height of s2 : "+ s2.getHeight());

//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

Using final to Prevent Inheritance

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 :

• Declaring a class as final implicitly declares all of its methods as final,


too.
• It is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to
provide complete implementations. For more on abstract classes,
refer abstract classes in java

Using final to Prevent Overriding

When a method is declared as final then it cannot be overridden by subclasses.


The Object class does this—a number of its methods are final. The following
fragment illustrates the final keyword with a method:

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.

Object Class in Java


•• =

Object class is present in java.lang package. Every class in Java is directly or
indirectly derived from the Object class. If a class does not extend any other
class then it is a direct child class of Object and if extends another class then it
is indirectly derived. Therefore the Object class methods are available to all
Java classes. Hence Object class acts as a root of the inheritance hierarchy in
any Java Program.

Using Object Class Methods

The Object class provides multiple methods which are as follows:


➢ tostring() method
➢ hashCode() method
➢ equals(Object obj) method
➢ finalize() method
➢ getClass() method
➢ clone() method
➢ wait(), notify() notifyAll() methods

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

public String toString()


{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
It is always recommended to override the toString() method to get our own
String representation of Object.

Note: Whenever we try to print any Object reference, then internally toString()
method is called.
Student s = new Student();

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());

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.

Use of hashCode() method


It returns a hash value that is used to search objects in a collection. JVM(Java
Virtual Machine) uses the hashcode method while saving objects into hashing-
related data structures like HashSet, HashMap, Hashtable, etc. The main
advantage of saving objects based on hash code is that searching becomes easy.
Note: Override of hashCode() method needs to be done such that for every
object we generate a unique number. For example, for a Student class, we can
return the roll no. of a student from the hashCode() method as it is unique.

// Java program to demonstrate working of hashCode() and toString()

public class Student {

static int last_roll = 100;


int roll_no;

// 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();

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());
}
}

Output :
Student@64
Student@64
Note that 4*160 + 6*161 = 100

3.equals(Object obj) method


It compares the given object to “this” object (the object on which the method is
called). It gives a generic way to compare objects for equality. It is recommended
to override the equals(Object obj) method to get our own equality condition on
Objects.

Note: It is generally necessary to override the hashCode() method whenever


this method is overridden, so as to maintain the general contract for the
hashCode method, which states that equal objects must have equal hash codes.

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.

// Java program to demonstrate working of getClass()


public class Test {
public static void main(String[] args)
{
Object obj = new String("GeeksForGeeks");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "
+ c.getName());
}
}
Output:
Class of Object obj is : java.lang.String
Note: After loading a .class file, JVM will create an object of the
type java.lang.Class in the Heap area. We can use this class object to get Class
level information. It is widely used in Reflection

5. finalize() method

This method is called just before an object is garbage collected. It is called


the Garbage Collector on an object when the garbage collector determines that
there are no more references to the object. We should override finalize() method
to dispose of system resources, perform clean-up activities and minimize memory
leaks. For example, before destroying the Servlet objects web container, always
called finalize method to perform clean-up activities of the session.
Note: The finalize method is called just once on an object even though that object
is eligible for garbage collection multiple times.

// Java program to demonstrate working of finalize()

public class Test {


public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.hashCode());

t = null;

// calling garbage collector


System.gc();

System.out.println("end");
}

@Override protected void finalize()


{
System.out.println("finalize method called");
}
}

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().

Example of using all the Object class methods in Java


import java.io.*;

public class Book implements Cloneable {


private String title;
private String author;
private int year;

public Book(String title, String author, int year)


{
this.title = title;
this.author = author;
this.year = year;
}

// Override the toString method


@Override public String toString()
{
return title + " by " + author + " (" + year + ")";
}

// Override the equals method


@Override public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof Book)) {
return false;
}
Book other = (Book)obj;
return this.title.equals(other.getTitle())
&& this.author.equals(other.getAuthor())
&& this.year == other.getYear();
}

// Override the hashCode method


@Override public int hashCode()
{
int result = 17;
result = 31 * result + title.hashCode();
result = 31 * result + author.hashCode();
result = 31 * result + year;
return result;
}

// Override the clone method


@Override public Book clone()
{
try {
return (Book)super.clone();
}
catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}

// Override the finalize method


@Override protected void finalize() throws Throwable
{
System.out.println("Finalizing " + this);
}

public String getTitle() { return title; }

public String getAuthor() { return author; }

public int getYear() { return year; }


public static void main(String[] args)
{
// Create a Book object and print its details
Book book1 = new Book(
"The Hitchhiker's Guide to the Galaxy",
"Douglas Adams", 1979);
System.out.println(book1);

// Create a clone of the Book object and print its


// details
Book book2 = book1.clone();
System.out.println(book2);

// Check if the two objects are equal


System.out.println("book1 equals book2: "
+ book1.equals(book2));

// Get the hash code of the two objects


System.out.println("book1 hash code: "
+ book1.hashCode());
System.out.println("book2 hash code: "
+ book2.hashCode());
// Set book1 to null to trigger garbage collection
// and finalize method
book1 = null;
System.gc();
}
}

Output

The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979)


The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979)
book1 equals book2: true
book1 hash code: 1840214527
book2 hash code: 1840214527

You might also like