⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 polymorphismexam.java

📁 Java程序设计实用教程源代码 本书源代码按章分别放置在不同的文件夹中,所有程序均在JDK1.6环境下编译运行正常,除了第13章需要建立ODBC数据源之外,其他程序只要有Java运行环境即可直接运行
💻 JAVA
字号:
package polymorphism;
class Pen {
  String color;
  int length;
  public Pen() { //默认构造函数,没有任何参数
  }
  Pen(String color) { //只有一个字符型参数color的构造函数
    this.color = color;
  }
  Pen(int length) { //只有一个数值型参数length的构造函数
    this.length = length;
  }
  Pen(String color, int length) { //有两个参数color和length的构造函数
    this.color = color;
    this.length = length;
  }
  void display() {  
    System.out.println("Pen’s color is " + color + ", length is " + length); 
  }

}
class myPen extends Pen {
  int weight;
  public myPen() {
  }
  myPen(String color, int weight) {
    super(color); //调用父类的构造函数Pen(String color)
    this.weight = weight;
  }
  myPen(int length, int weight) {
    super(length); //调用父类的构造函数Pen(int length)
    this.weight = weight;
  }
  myPen(String color, int length, int weight) {
    super(color, length); //调用父类的构造函数Pen(String color,int length)
    this.weight = weight;
  }
  void setWeight(int weight) {
    this.weight = weight;
  }
  int getWeight() {
    return this.weight;
  }
  void display() {  
    System.out.println("myPen’s color is " + color + ", length is " + length + ", weight is " + weight); 
  }
}
class Pencil extends Pen {
  public Pencil() {
  }
  Pencil (String color) {
    super(color); //调用父类的构造函数
  }
  Pencil (int length) {
    super(length); //调用父类的构造函数
  }
  Pencil (String color, int length) {
    super(color, length); //调用父类的构造函数
  }
  void display() {  
    System.out.println("Pencil’s color is " + color + ", length is " + length); 
  }
}
public class polymorphismExam {
  public static void main(String args[]) {
    Pen p1 = new Pen ("Red",23);
    Pen p2 = new myPen ("Yellow",67,120);
    Pen p3 = new Pencil("Green",47);
    p1.display();
    p2.display();
    p3.display();
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -