Skip to content
Advertisement

abstraction can be done without inheritance? java

Is abstraction possible without inheritance? This is my code

     abstract class whatever
{
    abstract void disp1();
    abstract void disp2();
    abstract void disp3();
}

 class what {

    void disp1()
    {
        System.out.println("This is disp1");
    }
}



public class threeClasses {

    public static void main (String args[])
    {
        what obj =new what();
        obj.disp1();

    }

}

Please note above, how i:

  1. did not extend the class “what” from abstract class “whatever” and yet the code runs perfectly with no errors
    1. Did not declare class “what” as abstract (since it’s not declaring the other two methods disp2() and disp3())

I am very confused. Please help.

Advertisement

Answer

There is no relationship between your abstract class and your concrete class. Whatever your definition of “abstraction”, it actually represents a relationship between types. The abstract keyword does not establish that relationship between classes, it represents that relationship, and not by itself. The relationship needs to be extended from both sides.

abstract is a declaration from one side about a promise that must be kept, for an inheriting type either to implement abstract methods or to ask for that promise from its inheriting types.

The other side makes the promise by being a class that inherits from the abstract type. Without inheritance, the concrete type loses the is-a connection.

You will get the compiler error you’re complaining about missing if you correct one major mistake you made. You failed to use the @Override annotation. Always use the @Override annotation when you intend to override a method, or you will forever enjoy just the sort of bug you show here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement