首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

请问关于多态的有关问题

2012-01-21 
请教关于多态的问题Java codepublic class Person {String namepersonpublic void shout(){System.out

请教关于多态的问题

Java code
public class Person {    String name="person";    public void shout(){        System.out.println(name);    }}public class Student extends Person{    String name="student";    String school="school";    }public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        Person p=new Student();        p.shout();    }}


为什么这里输出的是 person 而不是 student呢?

[解决办法]
Java code
public class Student extends Person {    Student(){        this.name = "student";        String school = "school";    }    }
[解决办法]
试试
Java code
public class Person {    String name="person";    public void shout(){        System.out.println(getName());//相当于this.getName(),属性相当于this.name 方法重写 属性隐藏 this类似于 Person this = new Student() this是Person类型引用     }    public String getName()    {           return name;    }}public class Student extends Person{    String name="student";    String school="school";    }public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        Person p=new Student();        p.shout();    }}
[解决办法]
Java code
interface Say {    public abstract void shout();}class Person {    String name = "Person";}class Student extends Person implements Say {    String name = "Student";    @Override    public void shout() {        // TODO Auto-generated method stub        System.out.println(name);    }}class Teacher extends Person implements Say {    String name = "Teacher";    @Override    public void shout() {        // TODO Auto-generated method stub        System.out.println(name);    }}public class Main {    public static void main(String[] args) {        // TODO Auto-generated method stub        Say personSay;        personSay = new Student();        personSay.shout();                personSay = new Teacher();        personSay.shout();    }}// result:/*StudentTeacher*/ 

热点排行