Access modifier | Accessable | Symbols in class diagrams |
---|---|---|
public | From anywhere | + |
protected | Classes and subclasses in the same package | # |
Classes in the same package | ~ | |
private | Current class | - |
Access from an unauthorized location will result in a ** compilation error **
・ ** Class ** (to determine if it can be accessed from another package) ・ Method -Collection (array, ArrayList) ·field
Since the interface is ** a prerequisite to be inherited **, the interface itself is implicitly considered ** public ** → Methods that can be defined in the interface -In the case of ** abstract method **, it is implicitly interpreted as ** public , abstract (public, abstract can be omitted). -If ** has an implementation, it must be ** static method ** or ** defalt method ** ( access modifiers are unlimited, private is also possible **)
→ Fields that can be defined in the interface -Static variables (** public only ) ・ Constant ( public only **) -Instance variables cannot be defined
** [Concrete method of class that implements interface] **
The access modifier of the abstract method ** defined in the interface and the concrete method ** that implements the abstract method in the class that implements the interface must be ** the same access modifier **. ..
Example) * A compilation error has occurred
interface A(){
void doSomething(); //Inderface abstract method. Implicitly interpreted as public
}
B implements A(){
protected void doSomething(){ //Compile error. Access modifier must be "public", same as the interface abstract method
//processing
}
}
Abstract classes (qualified with abstract) are implicitly considered ** public ** because abstract classes are ** inherited assumptions **
→ Methods that can be defined in abstract classes -For abstract methods, qualification with ** abstract ** is required. Since the abstract method is a method of ** premise to be overridden **, ** access modifier can be set other than private ** -For concrete methods, access modifiers can be set freely.
→ Fields that can be defined in the abstract class ・ No restrictions on settings
** * The access modifier when overriding the method should be the same as the original method or the restrictions should be relaxed **
Example)
interface A {
void doSomething();
}
abstract class B implements A {
public abstract void doSomething(); //The interface can be implemented with abstract methods. Access modifiers are the same as interface methods
}
class C extends B {
public void doSomething(){ //Override abstract method.
System.out.println("Do something");
};
}
public class Main {
public static void main(String[] args) {
C example = new C();
example.doSomething();
}
}
Recommended Posts