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呢?
Student(){
this.name = "student";
String school = "school";
}
}
还有你是想实现接口吧。这个模式是接口模式。
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();
}}
public class Student extends Person{
String name="student";
String school="school"; public void shout(){
System.out.println(super.name);
}
}
可以这样理解吗
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:
/*
Student
Teacher
*/