JaiswalTraining
Get the online training

Abstract classes and Interfaces

Abstract Class
  • An Abstract Class is a class that provides common behavior across a set of subclasses, but is not itself designed to have instances of its own
  • A class that dictates certain behavior but allows its subclasses to provide implementation
  • A class designed only as a parent from which sub-classes may be derived, but which is not itself suitable for instantiation
  • A class often used to "abstract out" incomplete sets of features which may then be shared by a group of sibling sub-classes which add different variations of the missing pieces
Rules

  • An Abstract Class cannot be instantiated
  • An abstract class can SHOULD be extended with extends keyword
  • An abstract class can have any number of abstract methods or none at all
  • A class with at least one abstract method must be declared an abstract class
  • A subclass can provide partial or full implementations of the inherited abstract methods
Inetrface
  • An Interface defines a contract by specifying a set of method prototypes for which each class that implements it must adhere
  • An interface is 100% abstract class
  • An interface provides only a form for a class but no implementation
  • An interface defines what a class can do but not how the class will do it
Use

  • A core reason for using interfaces is to be able to upcast to more than one base type
  • Several interfaces can be implemented by any class, thus resulting in multiple inheritance
  • implements keyword  is used with class which uses the interface.

Final class
  • final class can't be extended or subclass
  • final keyword is used  for this purpose
Example:1 Providing defintion for hello method in subclass

public abstract class bbbb {
abstract void hello();
int age=22;
}

abstract class dddd extends bbbb{
  
  abstract protected void disp();  
}

class ssss extends bbbb
{

@Override
public void hello() {
  age=11;  
  
  
}  
}


Example:2

interface  india1 {
  abstract void show();
  abstract void disp();
  char c='d';
}

class delhi1 {
    static String name="sss";
  public static void main(String[] args) {
    final int x=99
    india1 a = new india1() {
      int s=88;
      public void show() {
        System.out.println("in delhi "+x+s+name);
      }
      public void disp(){System.out.println("hi....."+c);}
    };
    a.show();
    a.disp();
  }
}
Output:-
java delhi1
in delhi 9988sss
hi.....d
Download code

Example:-3

public final class friend {
int roll=88;
  
void myjob(){}
}

class worstfriend{
  final void expense(){}
}

class bestfriend  extends worstfriend{
   void expense() {
  }
   
   void go(){     
    int r= new friend().roll=3;
    new friend().myjob();
 }  
}
Output:-

java friend
.java:12: expense() in bestfriend cannot override expense() in worstfriend
; overridden method is final
         void expense() {
              ^
1 error