62,616
社区成员
发帖
与我相关
我的任务
分享
class Human
{
protected String name;
protected int age;
public Human()
{
}
public Human(String name, int age)
{
this.name = name;
this.age = age;
}
public String getInfo()
{
return "Name:"+this.name+"\n"+"Age:"+this.age;
}
}
class Student extends Human
{
int banji;
String school;
int score;
public Student()
{
}
public Student(String name, int age, String school, int banji, int score)
{
super(name, age);
this.school = school;
this.banji = banji;
this.score = score;
}
public String getInfo()//这里的方法重新写一个不行吗?
{
return super.getInfo()+"\n"+"School:"+this.school+"\n"+"Class:"+this.banji+"\n"+"Score:"+this.score;
}
}
public class Test_Student {
public static void main(String[] args)
{
Student s = new Student("Ryahsa", 23, "Sichuan University of Art ant and Science", 3, 90);
System.out.print(s.getInfo());
}
}
class Cycle {
public String type() {
return "";
}
}
class Unicycle extends Cycle {
public String type() {
return "Unicycle";
}
}
class Bicycle extends Cycle {
public String type() {
return "Bicycle";
}
}
class Tricycle extends Cycle {
public String type() {
return "Tricycle";
}
}
public class Upcasting {
public static void ride(Cycle c) {
System.out.println("ride " + c.type());
}
public static void main(String[] args) {
Unicycle uc = new Unicycle();
Bicycle bc = new Bicycle();
Tricycle tc = new Tricycle();
ride(uc);
ride(bc);
ride(tc);
}
}
如果你不重写type方法而是重新写一个新的方法(把方法名改为type1,type2,type3),那么就实现不了上面程序的多态性,请看以下代码
class Cycle {
public String type() {
return "null";
}
}
class Unicycle extends Cycle {
public String type1() {
return "Unicycle";
}
}
class Bicycle extends Cycle {
public String type2() {
return "Bicycle";
}
}
class Tricycle extends Cycle {
public String type3() {
return "Tricycle";
}
}
public class Upcasting {
public static void ride(Cycle c) {
System.out.println("ride " + c.type());
}
public static void main(String[] args) {
Unicycle uc = new Unicycle();
Bicycle bc = new Bicycle();
Tricycle tc = new Tricycle();
ride(uc);
ride(bc);
ride(tc);
}
}