Java Class Description
Overloading and Overriding
Overloading: Same class, same method name, other parts different
Overriding: Parent-child class, same method name, (same name, two small, one big) same parameter list, return value, exception type, modifier
Interface and Abstract Class
| Feature | Abstract Class | Interface |
|---|---|---|
| Inheritance | Can only inherit one abstract class | Can implement multiple interfaces |
| Method Implementation | Can have implemented methods and abstract methods | Methods are abstract by default, can have default methods and static methods |
| Member Variables | Can have instance variables and static variables | Can only have constants (public static final) |
| Constructors | Can have constructors | Cannot have constructors |
| Access Modifiers | Can have multiple access modifiers | Methods are public by default (Java 9 introduced private) |
| Usage Scenarios | Suitable for sharing code, providing basic implementation | Suitable for expressing behavioral specifications, supporting multiple implementations |
Java 8 Interface New Features
CustomInterface.java
interface CustomInterface {
void abstractMethod(); //Abstract methods cannot be private
static void staticMethod() {
privateStaticMethod(); //public static method can call private static method
System.out.println("Static method called");
}
default void defaultMethod() {
privateMethod(); //Can call private method in interface
privateStaticMethod(); //Can call private static method in interface
System.out.println("Normal method called");
}
// this only can use java 9 or later version
private void privateMethod() {
System.out.println("private method called");
}
// this only can use java 9 or later version
private static void privateStaticMethod() {
System.out.println("private static method called");
}
}
Agreement
The code part of this work is licensed under Apache License 2.0 . You may freely modify and redistribute the code, and use it for commercial purposes, provided that you comply with the license. However, you are required to:
- Attribution: Retain the original author's signature and code source information in the original and derivative code.
- Preserve License: Retain the Apache 2.0 license file in the original and derivative code.
- Attribution: Give appropriate credit, provide a link to the license, and indicate if changes were made.
- NonCommercial: You may not use the material for commercial purposes. For commercial use, please contact the author.
- ShareAlike: If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.