abstract and final in java

Previous
Next

Can an abstract class be final?

  • If final – cannot be extended
  • If abstract – must be extended
  • Then final & abstract – become illegal combination of modifiers.
final abstract AbstractClass
{
	/* logic */
}
  • A method cannot be abstract & final.
  • Final method cannot be overridden.
  • Abstract method must be overridden
abstract class Test 
{
	abstract final void fun();
}
  • Abstract and static cannot be combined.
  • Only specific(non static in java) methods can be abstract.
  • Static method is common for all.
  • We cannot combine abstract and static.
abstract class Test 
{
	abstract static void fun();
}

Why abstract method cannot be static?

  • Common functionality of Object is static in java.
  • Abstract methods are specific(non-static) to particular object.
  • Hence both static (common) and abstract (specific) are illegal combination.
  • Static methods must have definition.
  • Static methods always concrete methods.
  • Static methods cannot participate in inheritance.

Can a Final class extend Abstract class?

Yes allowed.

abstract class AbstractClass
{
	// logic
}
final class FinalClass extends AbstractClass
{
	// logic
}

Note: FinalClass must override all abstract methods because final class cannot be extended.

abstract class AbstractClass
{
	abstract void m1();
	abstract void m2();
}
final abstract class FinalClass extends AbstractClass
{
	// Error : Override m1() and m2() as we cannot define final class as abstract
}

If we override all specifications, then compiler will not generate any error

abstract class AbstractClass
{
	abstract void m1();
	abstract void m2();
}
final class FinalClass extends AbstractClass
{
	void m1(){ }
	void m2(){ }
}
Previous
Next

Add Comment

Courses Enquiry Form