- 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*/