Search Logic Blocks

Friday, May 7, 2021

Java: Private Methods in an Interface

We have already learnt about the different kinds of methods in an Interface - We can have one more type of method in an interface - private method. Private methods in an interface work the same way as the private methods in a class. Private methods can't be accessed from outside of the Interface. Private methods are only accessed by the methods defined in the interface itself (default or static methods). The overridden methods in the implementing class also can not access the private methods.

Interface Private (Private.java)
public interface IPrivate {
public void msg();

default public void callMessage() {
message();
}

private void message() {
System.out.println("In private Method");
}
}
Class Test (Test.java)
public class Test implements IPrivate{
public void msg() {
//message();
System.out.println("In implementing class method");
}

static public void main(String args[]) {
Test test = new Test();
test.callMessage();
}
}
Conclusion - Here is the summary of different kinds of the methods in an interface -
  • Abstract methods (methods with an empty body) - Abstract methods are mandatory to be written / overridden by the implementing class. The implementing class should give structure to each abstract method in the interface.
  • Default methods (with the default code / instructions) - Default methods are not mandatory to be overridden by the implementing class, but if they are not overridden - the default method from the interface will be called.
  • Static methods (with the code) - Static methods are called directly by the interface itself, not by interface variable. So, static methods can't be overridden. If the implementing class has a method with the same name as the static method in the interface, there won't be any relation between two methods (static method in the interface and the same name method in the implementing class)
  • Private methods (with the code) - Private methods can only be accessed by default or static methods in the interface, not outside from the interface.
Code can be found at Github Link.

Thursday, May 6, 2021

Java: How to access interface methods using Interface References

In the earlier post Inheritance, we have already seen how all the child classes (Circle, Triangle and Rectangle) access the overridden methods, using the reference of the parent class (Shape). The compiler doesn't detect any difference, so there wouldn't be any compile time issues. When running the program, the JVM detects dynamically which class is referred to and accordingly the respective methods are called. This feature is called Polymorphism.


Same way, interface variables can refer its implementing classes. I have already shown this in the post Interfaces. The implementing classes (Triangle and Rectangle) are accessing the implemented methods, using the reference of the parent class (IPolygon).