关于继承和多态的实例程序及简要说明

/*
 * 关于继承中重写方法,调用成员变量和成员方法值得注意的参考实例和说明
 * */
class Father {
 String name;
 int age;

 public Father() {

 }

 public Father(String name, int age) {
  this.name = name;
  this.age = age;
 }

 public void show() {
  System.out.println("this is father");
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public void speak() {
  System.out.println(this.getName() + "    " + this.getAge());
 }
}

class Son extends Father {
 public Son() {
  super();
 }

 public Son(String name, int age) {
  super(name, age);
 }

 // 重写了show()
 public void show() {
  System.out.println("this is son");
 }
}

public class oop {
 public static void main(String[] args) {
  Father f = new Father("father", 45);
  Father fs = new Son("fson", 30);
  Son s = new Son("son", 12);
  System.out.println(f.name + "  " + fs.name + "   " + s.name);
  // 直接用引用调用,应该输出father fson son
  f.show();// 输出 this is father
  fs.show();// 输出this is son
  s.show();// 输出this is son
 }
}

猜你喜欢

转载自blog.csdn.net/jokerlance/article/details/75330041
今日推荐