Home > Enterprise >  Java abstract class and method implementation
Java abstract class and method implementation

Time:11-20

package javaPrac;

abstract public class Abstract_class_method {
    
    abstract void show(); //abstract methods requires abstract class and has no method .
    
    void calculate(int x, int y)
    {
        int calc = x   y;
        System.out.println("This is the normal method in abstract class " calc);
    }
    
//As per my knowledge there is no point of creating the main method within the abstract class as we cant able to create an object of the abstract class , so we either we need to use the extend keyword to extend it to other class or use the interface.
    
    public static void main(String[] args) {
        Abstract_class_method abobject = new Abstract_class_method() {
            
            @Override
            void show() {
                // TODO Auto-generated method stub
                System.out.println("This is the main method");
                
            }
        };
        abobject.show();
        abobject.calculate(10, 12);
    }

}

output This is the main method This is the normal method in abstract class 22

I am unable to understand the working of the main method as how in the main method I can able to make the object of the abstract class , correct me if I am wrong as the similar functionality is been observed when I am on working on anonymous classes in java.

Please provide explanation of the above code. You help is highly appreciated.

CodePudding user response:

Abstract classes are classes that a programmer intentionally designates as "incomplete". They are usually used for convenience - i.e. to provide a quick way of building your own class on top of something existing with minimal effort, and to hold the code that would normally be shared among all subclasses.

What you are doing is:

  • You have defined an abstract class, which by definition cannot be instantiated with new(). This class is missing a show() method, but provides a calculate() method.
  • In your main() method you are creating an anonymous subclass of your abstract class that actually implements the missing show() method. It also inherits calculate() method from its parent class.

CodePudding user response:

So the idea of an abstract class is to write a partial implementation of something which can be extended by your Concrete implementation.

Two issues with your code right now:

  1. Remove main method from abstract class.
  2. Have a public class in which you have main method implemented.
  • Related