简体   繁体   中英

Different rules for abstract methods in abstract class and interface

We cannot declare abstract methods in interface as protected and default (even if we don't mention any access specifier (default) compiler takes it as public)

but we can declare abstract method in abstract class as protected and default.

Why there are different rules for abstract class and interface?

Because abstract methods of abstract classes are meant to be hooks for subclasses. On the other hand interfaces are not concerned with implementation details - they are only about contracts with the "outside world". And a protected method is an implementation detail.

we cannot declare abstract methods in interface as protected and defaul

the purpose of Interface is to just declare contract. your client will implement it and for that it must be public .

also field in interface are public static final by default, public you got ,static because it can't be instantiated without implementation and it must not be inherited also.

Update: as per your question

you want to apply some strict constraint which your implementor can't see ..then what is the use of abstract method in abstract class that must be implemented by any concrete class in the inheritance hierarchy...then no one will be concrete class

public class BaseAbstractClass {
  private Connection getConnection(){
      //somecode 

  }

  public boolean save(){
      //get connection and do something 
      //return ;
  }

//your implementor is left to implement it , he  can use save method but can'ge see what it does i mean i doesn't have access to getConnection
  public abstract void saveEntity();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM