publicinterfaceMyInterface {
// Abstract methodvoidabstractMethod();
// Default methoddefaultvoiddefaultMethod() {
System.out.println("This is the default method of the interface");
privateHelperMethod(); // Call private helper method (Note: private methods are a Java 9 feature, shown here for example only) }
// Static methodstaticvoidstaticMethod() {
System.out.println("This is the static method of the interface");
}
// Private helper method (Java 9 feature, but included for completeness)privatevoidprivateHelperMethod() {
System.out.println("This is the private helper method of the interface");
}
}
publicclassMyClassimplements MyInterface {
@OverridepublicvoidabstractMethod() {
System.out.println("Implementing the abstract method of the interface");
}
// Can choose to override the default method@OverridepublicvoiddefaultMethod() {
System.out.println("Overriding the default method of the interface");
MyInterface.super.defaultMethod(); // Call the default method of the interface }
}
publicclassMain {
publicstaticvoidmain(String[] args) {
MyClass myClass =new MyClass();
// Call the implemented abstract method myClass.abstractMethod();
// Call the default method myClass.defaultMethod(); // Note that the overridden version is called here// Call the static method of the interface MyInterface.staticMethod();
}
}
Abstract Class
Abstract classes typically serve as base classes, such as Person, Animal. Because the body of certain methods may differ among various subclasses, these methods are placed as abstract methods in the abstract class.
An abstract class can inherit from another class and can implement multiple interfaces.
Sing and Dance both represent capabilities, so they are interfaces implemented by the Animal abstract class.
The Animal class provides the abstract method eat().
The Cat and Dog classes then provide different method bodies for the eat() method.
Autoboxing & Unboxing
Autoboxing:
Automatically converts primitive types to their corresponding wrapper class objects, actually calling methods like Integer.valueOf(), Double.valueOf(), etc.
1
2
int num = 10;
Integer boxedNum = num; // Autoboxing (int → Integer)
Unboxing: Automatically converts wrapper class objects to primitive types. Actually calls methods like intValue(), doubleValue(), etc.
Performance issues: Autoboxing/unboxing creates temporary objects, and frequent use in loops can lead to performance degradation.
When comparing wrapper class objects, == compares memory addresses, not values!
1
2
3
4
5
6
7
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true (JVM caches small integer objects)Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false (outside cache range, new objects created)