还在懵逼重写和重载吗?
知道为什么叫继承之方法的重写,我怕我以后搞混重写和重载,干脆将继承和重写放一块。
(=_=)那就多看,多想。之前有一篇文章:【Java查漏补缺(二)】面向对象 | SilverSucks (weiswift.github.io)
方法的重载
概述
方法重载:
- 在同一个类中, 出现方法名称相同, 但是参数列表不同的(个数不同,对应的数据类型不同)的两个或多个方法
- 方法重载与返回值的数据类型无关
应用场景
用来解决功能相似或相同, 但是方法名不能重名的问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class OverLoaded {
public static void main(String[] args) { boolean flag = compare(10, 20); System.out.println(flag); short s1 = 11, s2 = 22; compare(s1, s2);
}
public static boolean compare(byte b1, byte b2) { System.out.println("比较byte类型"); return b1 == b2; } public static void compare(short b1, short b2){ System.out.println("比较short类型"); System.out.println(b1 == b2); } public static boolean compare(int b1, int b2){ System.out.println("比较int类型"); return b1 == b2; } public static boolean compare(long b1, long b2){ System.out.println("比较long类型"); return b1 == b2; } }
|
方法的重写
提到重写,一般大多指的是在父类继承子类方法的时候,不满足于父类方法,而对方法进行的override。
在子父类中,子类拥有了和父类一样声明的方法,可以让调用者不改变调用方式的前提下,得到更强大的功能!
重写的注意事项

CodeDemo
Phone-父类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package com.xlkh.demo07_methodOverride;
public class Phone { private String brand; private double price;
public Phone(String brand, double price) { this.brand = brand; this.price = price; }
public Phone() { }
public String getBrand() { return brand; }
public double getPrice() { return price; }
public void setBrand(String brand) { this.brand = brand; }
public void setPrice(double price) { this.price = price; } public void call(){ System.out.println(price + "元的" + brand + "手机正在打电话!"); } }
|
NewPhone-子类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.xlkh.demo07_methodOverride;
public class NewPhone extends Phone{
@Override public void call() { System.out.println("播放彩铃"); super.call(); System.out.println("祝福语..."); } }
|
TestPhone-测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.xlkh.demo07_methodOverride;
public class NewPhone extends Phone{
@Override public void call() { System.out.println("播放彩铃"); super.call(); System.out.println("祝福语..."); } }
|