top of page
Search

Java - Abstract class , Type Casting of Objects and Final keyword

What is an Abstract class in Java?

Abstract class can be used only for inheritance. It is not possible to create object of an abstract class even if, it has instance variables and constructor. But, references of abstract class can be used to derived class objects.

Abstract class can have instance variables, constructors and other methods including static members.

For Abstract class to be meaningful, it must have at-least one abstract method. But, this is not compulsion (means abstract class may not have any method declared as abstract).

If abstract class has abstract method, it cannot be private, protected or default. It has tp be compulsorily public.

It is must to override all abstract methods in derived class.

How we can compare two objects in Java?

Object class provides equals() method to compare two objects. This method compares two object references and if they are referring to same memory , it returns true, else false.

Product p1 = new Product();

Product p2 = p1;

If (p1.equals(p2)) // result TRUE


Product p1 = new Product();

Product p2 = new Product();

If (p1.equals(p2)) // result FALSE


If you have to compare two object references holding two different objects , located in different memory location, you have to override equals() method,


What is object type casting in Java?

Java supports typecasting of objects from base class to derived class and vice-versa. Casting of object from subclass (derived class) to superclass (base class) is implicit (automatic) in Java. Following example shows how it works.

class Employee { .... }

class Manager extends Employee { ....}

Manager m = new Manager();

Employee e = m; // Manager to Employee implicit type casting but, methods from Manager class are not available using object e.


To type cast super class object to its subclass , we need to use explicit typecasting.

Employee e = new Manager();

Manager m = (Manager) e; // allowed in java


Please note that, object of superclass cannot be typecasting to subclass, it will result into ClassCastException

For example,

Employee e = new Employee();

Manager m = (Manager) e; //ClassCastException will be generated

What is final keyword used for?

Final keyword can be used for three purposes as follows:

    Want to read more?

    Subscribe to questionbankos.com to keep reading this exclusive post.

     
     
     
    bottom of page