This is a common interview question for Java freshers as well as mid-level experienced professionals.
Abstract Class:
An abstract class cannot be instantiated. In other words, you cannot create an object of an abstract class directly, even if it has a constructor and all of its methods are implemented. An abstract class can contain both abstract and non-abstract methods. An abstract method is declared without an implementation and must be implemented by a subclass. Theabstract keyword is used to declare an abstract class.See the example below:
abstract class Employee{ } class Salary { public static void main(String[] args) { Employee emp=new Employee(); //it will give the compile time error. } }
Although an abstract class cannot be instantiated directly, you can create a reference of the abstract class that points to an object of its subclass. The subclass extends the abstract class and provides implementations for all of its abstract methods.
For example:
abstract class Employee{ abstract void method1(); public void method2(){ //some statements } } class Salary extends Employee { public void method1(){ System.out.println("method1....."); } } class MainExample{ public static void main(String[] args){ Employee e=new Salary(); e.method1(); //it will call method1 of Salary class. } }
Rules for Abstract Classes
A class can be declared as
abstractwithout containing any abstract methods. However, if a class contains even one abstract method, it must be declared as an abstract class.An abstract class can contain one or more abstract methods.
An abstract class can contain both abstract methods and non-abstract (concrete) methods.
A subclass that extends an abstract class must either implement all of the abstract methods inherited from the superclass or be declared as an abstract class itself.
Interface :
An interface is not a class; it defines a contract that a class can implement. Traditionally, an interface contains only abstract methods (methods without implementation), although since Java 8, it can also contain
default and static methods, and since Java 9, it can contain private methods. The interface keyword is used to declare an interface.All variables declared in an interface are implicitly public, static, and final, making them constants.
An interface cannot have constructors because it cannot be instantiated directly. Additionally, an interface can extend one or more other interfaces, allowing multiple interface inheritance.
public interface InterfaceEx{ int a=10; //it is equivalent to public static int a=10; public void method1(); }
Thank you for visiting our blog!
No comments:
Post a Comment