abstract class Person
{
private String name ;
private int age ;
public Person(String name,int age)
{
this.setName(name) ;
this.setAge(age) ;
}
public void setName(String name)
{
this.name = name ;
}
public void setAge(int age)
{
this.age = age ;
}
public String getName()
{
return this.name ;
}
public int getAge()
{
return this.age ;
}
// 将说话的内容作为一个抽象方法,通过子类去实现
public void say()
{
System.out.println(this.getContent()) ;
}
public abstract String getContent() ;
};
// 假设人分为两种 :一种是工人,一种是学生
// 工人有工资,学生有成绩
// 不管是学生还是工人,肯定都可以说话
// 说话的内容不一样
class Worker extends Person
{
private float salary ;
public Worker(String name,int age,float salary)
{
super(name,age) ;
this.setSalary(salary) ;
}
public void setSalary(float salary)
{
this.salary = salary ;
}
public float getSalary()
{
return this.salary ;
}
public String getContent()
{
return "工人说 --> 姓名:"+super.getName()+",年龄:"+super.getAge()+",工资:"+this.getSalary() ;
}
};
class Student extends Person
{
private float score ;
public Student(String name,int age,float score)
{
super(name,age) ;
this.setScore(score) ;
}
public void setScore(float score)
{
this.score = score ;
}
public float getScore()
{
return this.score ;
}
public String getContent()
{
return "学生说 --> 姓名:"+super.getName()+",年龄:"+super.getAge()+",成绩:"+this.getScore() ;
}
};
public class OODemo03
{
public static void main(String args[])
{
Person p = null ;
// p = new Student("张三",30,90) ;
p = new Worker("张三",30,3000) ;
p.say() ;
}
};
这边的p = new Worker("张三",30,3000) ;是不是对p进行实例化了?p是抽象类对象呀,不是不可以的么?

解决方案 »

  1.   

    你的意思是p只是new Worker("张三",30,3000) 的引用吗?
      

  2.   

    都是说的1L提出的那个问题,LZ先弄明白了
      

  3.   


    这个能看出来不?
    public interface T() {
    }
    public class TT implements T {}
    T t = new TT();父类引用指向子类对象。
      

  4.   

    this指的肯定是具体的Worker或者Student对象,只是用Person作为引用
      

  5.   

    抽象是谓某类实体的共有特性,对吗,比如狼虫虎豹都可以抽象出动物的特性,那是不是也可以用动物去分别描述它们?java语言设计者的初衷,就是为了让语言面向对象特性,按这个原则设计
      

  6.   

    父类引用指向子类对象啊.P是引用,new Student()才是对象.
      

  7.   

    你实际上实例化的是worker的对象,new的是worker不People。你学了C++后就会更加了解这些概念了,我正在学习JAVA,还在旁边学习C++。
      

  8.   

    编译时是引用PEOPLE,执行时就变成了WORKER了。