Understanding Inheritance
1. Creating Subclasses
Example: extends
public class Animal {
protected String name;
public Animal(String name) { this.name = name; }
public void speak() { System.out.println("..."); }
}
public class Dog extends Animal {
public Dog(String name) { super(name); }
@Override public void speak() { System.out.println("Woof"); }
}
| Rule | Detail |
|---|---|
| Single inheritance | One direct superclass; multiple interfaces allowed |
| Default super | java.lang.Object |
| Inherits | All non-private members |
2. Using super Keyword
| Form | Use |
|---|---|
super.method() | Call parent's overridden method |
super.field | Access parent field (when shadowed) |
super(args) | Invoke parent constructor (first stmt) |
3. Overriding Methods
| Requirement | Detail |
|---|---|
| Same signature | Name + parameter types |
| Return type | Same or covariant subtype |
| Access | Same or wider |
| Checked exceptions | Same or narrower; cannot add new |
| Annotation | @Override recommended |
4. Understanding Method Overriding Rules
| Cannot Override | Reason |
|---|---|
final methods | Locked |
static methods | Hidden, not overridden |
private methods | Not visible; defines new method |
| Constructors | Not inherited |
5. Calling Parent Constructors (super())
| Aspect | Detail |
|---|---|
| Position | First statement (or implicit) |
| Implicit call | Compiler inserts super() if no explicit call |
| No-arg required | Parent must have accessible no-arg constructor (or call explicit) |
6. Understanding Constructor Chaining
| Step | Action |
|---|---|
| 1 | Super constructor chain runs first |
| 2 | Instance initializers + field defaults run |
| 3 | Subclass constructor body runs |
7. Using final Keyword
| Applied to | Effect |
|---|---|
| Class | Cannot be subclassed |
| Method | Cannot be overridden |
| Field | Assignable once |
| Local var/parameter | Cannot reassign |
8. Understanding Object as Root Class
| Inherited Method | Override? |
|---|---|
equals, hashCode, toString | Usually yes |
getClass, wait, notify | final — cannot |
clone | If implementing Cloneable |
9. Working with instanceof and Type Checking
| Form | Notes |
|---|---|
x instanceof T | Returns boolean |
x instanceof T t JAVA 16+ | Pattern variable; auto-cast |
10. Understanding Covariant Return Types
Example: Covariant return
class Shape { Shape copy() { return new Shape(); } }
class Circle extends Shape {
@Override Circle copy() { return new Circle(); } // narrower return
}
| Rule | Detail |
|---|---|
| Subclass return | May be subtype of parent's return type |
| Caller benefit | No cast needed when calling on subtype reference |
11. Understanding Method Overloading vs Overriding
| Aspect | Overloading | Overriding |
|---|---|---|
| Scope | Same class | Subclass replaces parent |
| Signature | Different params | Same params |
| Return type | Any | Same/covariant |
| Resolution | Compile-time (static) | Runtime (dynamic) |
| Polymorphism | Compile-time | Runtime |