📄 polymorphismexam.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 + -