在Java中分配参考变量(示例)

有两节课:



/**

 * This class models a person.

 *

 * @author author name

 * @version 1.0.0

 */

public class Person  {


    /* Name of the person */

    private String  name;


    /* Address of the person */

    private String  address;


    /**

     * Constructs a <code>Person</code> object.

     *

     * @param initialName  the name of the person.

     * @param initialAddress  the address of the person.

     */

    public Person (String initialName, String initialAddress) {


        name = initialName;

        address = initialAddress;

    }


    /**

     * Returns the name of this person.

     *

     * @return the name of this person.

     */

    public String getName() {


        return this.name;

    }


    /**

     * Returns the address of this person.

     *

     * @return the address of this person.

     */

    public String getAddress() {


        return this.address;

    }

}

员工是一个人,因此每个Employee对象也是一个Person对象。因此,可以将Employee参考变量分配给Person参考变量。

人员人员=新员工(“乔·史密斯”,“大街100号”,3000.0);

但是也可以将其分配给Employee参考变量吗?

雇员雇员=新雇员(“乔·史密斯”,“主大街100号”,3000.0);

如果是,那么两者之间有什么区别。我想掌握引用和分配变量的想法,因此我非常感谢您进行澄清。


慕仙森
浏览 162回答 3
3回答

当年话下

(1)&nbsp;Person&nbsp;person&nbsp;=&nbsp;new&nbsp;Employee("Joe&nbsp;Smith",&nbsp;"100&nbsp;Main&nbsp;Ave",&nbsp;3000.0); (2)&nbsp;Employee&nbsp;employee&nbsp;=&nbsp;new&nbsp;Employee("Joe&nbsp;Smith",&nbsp;"100&nbsp;Main&nbsp;Ave",&nbsp;3000.0);两者都是正确的。(1)创建一个Employee,然后将其放入一个person对象。您会丢失员工字段/方法,但可以通过以下方式进行强制转换:Employee employeeFromPerson=(Employee)person。您只能引用person方法而不进行强制转换。(2)基本创建一个雇员并将其放入一个雇员对象中。您可以使用此对象引用Person和Employee方法/字段。

慕森王

两者都是正确的,并且都引用了雇员对象,但是都在不同的场景中使用。首先用于动态多态性,其次用于简单对象分配。例如,让我们假设在这种情况下,两个类Employee和Student扩展了Person类,并且都覆盖了相同的方法。区别在于在运行时调用哪种方法。class Person {&nbsp; &nbsp; public String getTag(){&nbsp; &nbsp; &nbsp; &nbsp; return "This is Person"&nbsp; &nbsp; }}class Employee extends Person {&nbsp; &nbsp; public String getTag(){&nbsp; &nbsp; &nbsp; &nbsp; return "This is Employee"&nbsp; &nbsp; }}class Student extends Person {&nbsp; &nbsp; public String getTag(){&nbsp; &nbsp; &nbsp; &nbsp; return "This is Student"&nbsp; &nbsp; }}Person person1 = new Person();Person person2 = new Employee();Person person3 = new Student();Employee employee = new Employee();Student student = new Student();person1.getTag(); //it will return "This is Person"person2.getTag(); //it will return "This is Employee"person3.getTag(); //it will return "This is Student"employee.getTag(); //it will return "This is Employee"student.getTag(); //it will return "This is Student"注意person2和person3引用了子类对象,它将调用子类方法的定义而不是其自身方法的定义

MMMHUHU

真的没关系。您可以使用任何一个。如果您拥有的类A和子类,A&nbsp;B并且只想使用A的功能,请使用A a = new B();。但是,如果使用的数组Person,则情况有所不同。如果你有Person超级类Manager和Employee作为子类,那么你可以把任何类型的人进入Person[]。但是,如果创建数组Manager[],则不能Employee在其中放一个。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java