【问题标题】:Object creation for other class [duplicate]为其他类创建对象[重复]
【发布时间】:2019-08-03 20:39:05
【问题描述】:

为什么我们创建一个类的对象并分配给不同类的引用类型。我有两个班级说员工和学生,创建对象的目的是什么

Employee emp = new Student();

这是如何工作的?在什么情况下我们会创建这样的对象?

【问题讨论】:

  • 很多原因。也许您想阻止调用在 Student 中声明但在 Employee 中不存在的方法。也许你正在编码接口,..
  • 开始here

标签: java


【解决方案1】:

假设有两个班级EmployeeStudent。根据你的例子

Employee emp=new Student()

Employee类应该是父类,Student类是子类。假设孩子访问父母的成员。就是这样;

class Employee{
    String empName = "John";
}

class Student extends Employee{ 
   int age = 20;
}



class Test{
   public static void main(String[] args){

     Student s= new Student();
     System.out.println(s.empName);  //valid since child class can access members of 
                                                                     parent class 

     System.out.println(s.age);  //valid

     Employee emp=new Student();  //your example
     System.out.println(emp.empName); //valid
     System.out.println(emp.age);  //not valid since parent class can't access child members

 }
}

【讨论】:

    猜你喜欢
    • 2017-04-22
    • 2017-05-12
    • 2011-07-21
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多