日期:2014-05-20 浏览次数:20986 次
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();
}
}
public class Student extends Person {
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();
}
}
------解决方案--------------------
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:
/*
Student
Teacher
*/