课堂回顾:重载和继承
重载:
1 package org.hanqi.pn0120; 2 3 public class Jisuanqi { 4 5 //整型加法 6 public int add(int a,int b) 7 { 8 return a+b; 9 } 10 //重载 参数个数不同 11 public double add(int c, int d,int e) 12 { 13 return c+d+e; 14 } 15 16 17 //浮点型加法 方法的重载(多态的一种体现) 18 //参数类型不同 19 public double add(double a,double b) 20 { 21 return a+b; 22 } 23 24 public static void main(String[] args) { 25 // TODO Auto-generated method stub 26 Jisuanqi j=new Jisuanqi(); 27 System.out.println("20+50="+j.add(20, 50)); 28 System.out.println("20.12+50.45="+j.add(20.12, 50.45)); 29 } 30 31 }
继承:
Father类代码:
1 package org.hanqi.pn0120; 2 3 public class Father { 4 5 private String name; 6 private int age; 7 public String getName() { 8 return name; 9 } 10 public void setName(String name) { 11 this.name = name; 12 } 13 public int getAge() { 14 return age; 15 } 16 public void setAge(int age) { 17 this.age = age; 18 } 19 20 public Father() 21 { 22 System.out.println("父类的构造方法"); 23 } 24 25 //工作 26 public void work() 27 { 28 System.out.println("我劳动我光荣"); 29 } 30 }
Son类代码:
1 package org.hanqi.pn0120; 2 3 public class Son extends Father { 4 //Object a; 所有类的父类 5 public Son() 6 { 7 System.out.println("子类的构造方法"); 8 } 9 public void sing() 10 { 11 System.out.println("我喜欢唱歌"); 12 } 13 //覆盖(重写) 14 public void work() 15 { 16 System.out.println("我不喜欢上班,我要去参加海选"); 17 } 18 }
Test类代码:
1 package org.hanqi.pn0120; 2 3 public class Testjicheng { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 8 Father f=new Father(); 9 f.setName("父亲"); 10 f.setAge(50); 11 System.out.println("名字是:"+f.getName()+" 年龄是:"+f.getAge()); 12 f.work(); 13 System.out.println(); 14 Son s=new Son(); 15 s.setName("儿子"); 16 s.setAge(20); 17 System.out.println("名字是:"+s.getName()+" 年龄是:"+s.getAge()); 18 s.work(); 19 s.sing(); 20 } 21 22 }