简体   繁体   English

父类可以不同于子类吗?

[英]Could a superclass differ to subclasses?

Lets say we have: 可以说我们有:

1) Superclass containing a string parameter: companyName 2) Subclasses containing string parameters: firstName, lastName 1)包含字符串参数的超类:companyName 2)包含字符串参数的子类:firstName,lastName

If we have subClassA, subClassB, subClassC, subClassD, etc. Can these subclasses have same superclass, but with different strings companyName, or the companyName meaning/value will be the same for every subclass no matter what? 如果我们有subClassA,subClassB,subClassC,subClassD等。这些子类可以具有相同的超类,但是具有不同的字符串companyName,或者每个子类的companyName含义/值都相同吗?

Every instance of the parent class can have a different value for companyName whether it's of a subtype or not. 父类的每个实例的companyName可以具有不同的值,无论它是否属于子类型。

public class Parent {
  private final String companyName;

  public Parent(String name) {
    this.companyName = name;      // ignoring error-checking here
  }

  public String getCompanyName() {
    return companyName;
  }
}

public class Subsidiary extends Parent {
  private final String subsidiaryName;

  public Subsidiary(String parentName, String subsidiaryName) {
    super(parentName);
    this.subsidiaryName = subsidiaryName;
  }

  public String getSubsidiaryName() {
    return subsidiaryName;
  }
}

In some client code you can call: 在某些客户端代码中,您可以调用:

Subsidiary subsidiary = new Subsidiary("Holdings, Inc.", "Puppet");
System.out.println(subsidiary.getCompanyName() + " owns "
    + subsidiary.getSubsidiaryName());

You see, the child-type object inherits the accessor method getCompanyName that gives it access to the information in the parent section of the object. 您会看到,子类型对象继承了访问器方法getCompanyName ,该方法使它可以访问对象的父部分中的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM