方法覆盖示例:
public class OverrideTest01{ public static void main(String[] args){ //ChinaPeople cp = new ChinaPeople("张三"); //错误: 子类无法继承父类的构造方法; ChinaPeople cp = new ChinaPeople(); cp.setName("张三"); cp.speak(); AmericPeople ap = new AmericPeople(); ap.setName("tom"); ap.speak(); } } class People{ String name; //实例属性 public People(){ //构造方法 } public People(String name){ this.name = name; } //setter and getter public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void speak(){ System.out.println(name + " ....."); } } class ChinaPeople extends People{ public void speak(){ //重写父类的speak方法 System.out.println(this.getName() + "正在说汉语。"); } } class AmericPeople extends People{ public void speak(){ System.out.println(this.getName() + " is speaking."); } }
重写Object类中的toString()方法:
public class OverrideTest02{ public static void main(String[] args){ MyDate md = new MyDate(); System.out.println(md.toString()); //MyDate@512ddf17,默认输出对象在堆中的内存地址 System.out.println(md); //MyDate@512ddf17,对象后不带toString()输出结果一样,默认输出对象在堆中的内存地址 MyDate md1 = new MyDate(); //重写toString()方法后,“对象.toString()” 可以输出符合要求的年月日格式; System.out.println(md1.toString()); System.out.println(md1); } } class MyDate{ //MyDate类默认继承Object类,所以会默认继承Object类的toString()方法 private int year; private int month; private int day; public MyDate(){ this(1970,1,1); } public MyDate(int year, int month, int day){ this.year = year; this.month = month; this.day = day; } public void setYear(int year){ this.year = year; } public int getYear(){ return year; } public void setMonth(int month){ this.month = month; } public int getMonth(){ return month; } public void setDay(int day){ this.day = day; } public int getDay(){ return day; } public String toString(){ //重写Object类中的toString方法 return year + "年" + month + "月" + day + "日"; } }
浙公网安备 33010602011771号