简体   繁体   English

从超类调用一个子类方法,该方法在另一个子类中不可用

[英]Call a subclass method from superclass which is not available in another sub class

I have a superclass Person and two subclasses Author and Member as follows 我有一个超类Person和两个子类AuthorMember ,如下所示

public class Author extends Person {    
  public Author(String fName, String lName, int noOfPublications){
      ----// set 
  }    
   public String getnoOfPub(){
     return noOfPublications;
  }
}

public class Member extends Person {

public Member(String fName, String lName, int memberNo){
----// set 
}    
 public String getMembNo(){
        return memberNo;
    }
}

I want to access the non common methods from main class or How can I get access to getnoOfPub and getMembNo methods from superclass person? 我想从主类访问非通用方法,还是要如何从超类人员访问getnoOfPub和getMembNo方法?

You can gain access to the non-common methods by checking the type of the object and casting it to the type of the relevant sub-class, but that's not something you'd want to do in the code of the base class. 您可以通过检查对象的类型并将其转换为相关子类的类型来访问非常用方法,但这不是您想要在基类代码中执行的操作。

In a method of Person, you can write : 使用Person的方法,您可以编写:

public void someMethod ()
{
    String id = null;
    if (this instanceof Member) {
        Member member = (Member) this;
        id = member.getMembNo ();
    }
}

While this is valid syntax, it's a very bad practice, since the base class shouldn't know about its sub-classes, since the sub-classes can be written long after the base-class was written, so the writers of the base-class can't assume they know all the sub-classes that would extend their base-class. 尽管这是有效的语法,但是这是一个非常不好的做法,因为基类不应该知道其子类,因为子类可以在编写基类之后很长时间才能编写,因此基类的作者类不能假设他们知道将扩展其基类的所有子类。

it is difficult to answer the question because it is very broad. 这个问题很广泛,很难回答。 but i'll answer the common mistakes: 但我会回答常见的错误:

  1. it might be that you want a method in the superclass to be override in the sub class. 可能是您希望超类中的方法在子类中被覆盖。
  2. you need to cast from Person to the subclasses Member or Author and the use your methods. 您需要从Person转换为MemberAuthor子类,并使用您的方法。
  3. you need to initiate a variable of Member or Author and then use the methods. 您需要启动MemberAuthor的变量,然后使用这些方法。
  4. not very likely but might be - you want the method to be static 不太可能,但可能是-您希望方法是静态的

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

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