Static Methods
A static method is hidden, not overridden when a subclass defines a static method with the same name.
class Animal {
static void test() {
System.out.println("Animal");
}
void show() {
System.out.println("Animal instance");
}
}
class Cat extends Animal {
static void test() {
System.out.println("Cat");
}
@Override
void show() {
System.out.println("Cat instance");
}
}
Cat cat = new Cat();
Animal animal = cat;
Animal.test(); // Animal
animal.show(); // Cat instance
Remember:
staticmethod → hidden → depends on reference/class type
instance method → overridden → depends on actual object
Interface Methods
Interfaces can have default methods with implementations.
interface Flyer {
default void show() {
System.out.println("I can fly");
}
}
interface Swimmer {
default void show() {
System.out.println("I can swim");
}
}
If a class implements both, Java doesn't know which show() to use.
class Duck implements Flyer, Swimmer {
@Override
public void show() {
Flyer.super.show();
}
}
Now:
Duck duck = new Duck();
duck.show();
Output:
I can fly
Important Rules
1. Class method wins over interface default method.
class Animal {
void show() {
System.out.println("Animal");
}
}
interface Flyer {
default void show() {
System.out.println("Flyer");
}
}
class Bird extends Animal implements Flyer {
}
Animal.show() is used.
2. Two interfaces with the same default method → class must override it.
class Duck implements Flyer, Swimmer {
@Override
public void show() {
Flyer.super.show();
}
}
You can choose an interface's default method using:
Flyer.super.show();
3. Static methods in interfaces are NOT inherited.
interface Animal {
static void test() {
System.out.println("Animal");
}
}
Call it using:
Animal.test();
Not:
someObject.test(); // ERROR
Easy Summary
Static methods → hidden, not overridden.
Instance methods → overridden.
Class method beats interface default method.
Conflicting interface defaults → subclass must override.
Interface static methods → not inherited.