Java重写与重载:方法的‘改头换面’与‘改头换面’,必分清
Java中方法重载与重写是重要特性,初学者易混淆,核心区别如下: **方法重载(Overload)**:同一类中,方法名相同但参数列表不同(类型、数量或顺序),返回值、修饰符等可不同。目的是同一类中提供多参数处理方式(如计算器add方法支持不同参数相加),仅参数列表决定重载,返回值不同不算重载。 **方法重写(Override)**:子类对父类方法的重新实现,要求方法名、参数列表完全相同,返回值为父类返回值的子类,访问权限不低于父类。目的是子类扩展父类功能(如狗重写动物叫方法),静态方法不可重写(只能隐藏)。 **核心区别**:重载看参数不同(同一类),重写看继承(参数相同)。记住:重载“换参数”,重写“换实现”。
Read MoreJava super Keyword: Calling Parent Class in Inheritance, Must-Know
`super` is a keyword in Java used to access a parent class's members from a subclass, with the core role of connecting the subclass and the parent class. **1. Calling the parent class constructor**: The subclass constructor by default first calls the parent class's no-argument constructor (`super()`). If the parent class has no no-argument constructor or a parameterized constructor needs to be called, `super(parameters)` must be explicitly used and **must be placed on the first line of the subclass constructor**, otherwise a compilation error will occur. **2. Accessing parent class member variables with the same name**: When a subclass variable has the same name as a parent class variable, the subclass variable is accessed by default. Using `super.variableName` explicitly accesses the parent class variable. **3. Calling the parent class's overridden method**: After a subclass overrides a parent class method, the subclass method is called by default. Using `super.methodName()` calls the parent class's overridden method. **Notes**: `super` cannot be used in static methods; `super()` must be on the first line of the subclass constructor; `this()` and `super()` cannot be used simultaneously in a constructor. Mastering `super` enables clear control over a subclass's access to a parent class's members and is key to understanding Java inheritance.
Read More