Why I am not getting any error in below code?

Harshal :

Below is my code.

public abstract class AbstractClass {

    public String publicMethod() {
        System.out.println("This is Public Method");
        return "This is Public Method";
    }

    abstract  public String abstractMethod();
}



public class ConcreteClass extends AbstractClass{

    @Override
    public String abstractMethod() {
        String str = "This is abstract method implementtation in ConcreteClass";
        System.out.println(str);
        return str;
    }

    public String abstractMethod(String string) {
        String str = "This is overloaded method abstractMethod in ConcreteClass";
        System.out.println(str);
        return str;
    }

    public String publicMethod() {
        System.out.println("This is Public Method in ConcreteClass");
        return "This is Public Method in ConcreteClass";
    }

}

So I have public String publicMethod() method in abtract class as well as in class extending that abstract class. Also I have not given @Override annotation. Why no error given ? Also is this method overriding or publicMethod is getting ignored ?

Eran :

@Override is an optional annotation. If you are using this annotation for a method that doesn't override a super-class method and doesn't implement an interface method, the compiler gives an error.

However, it is allowed to override a method without marking it with that annotation (though using that annotation is useful, since it can catch errors when you intend to override a method but get the signature of the method you intend to override wrong).

Yes, your sub-class's publicMethod() overrides the super-class method of the same name.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307980&siteId=1