简体   繁体   中英

java why is this method not visible

Why is getPlatformId() not visible to SalesforcePlatform in the subclass method getPlatformName() ? The code block is not complete. SalesforcePlatform is a child of Platform . It is in a different package than Platform , but that should not prevent it from accessing Platform's protected method, right?

Sorry if I missed something obvious.

package com.dragon.dictionary;

public class Platform extends RepositoryObject
  implements IPlatform{

  protected final Long id ;
  protected final String  name;
  protected static final String platformDbTbl = DragonConstants.TABLE_PREFIX + "platform";


  protected Platform(Long platformId, String platformName){
    id = platformId;
    name = platformName;
  };

  protected Platform(String platformName){
    Platform platform = Platform.getPlatformByName(platformName);
    id = platform.getPlatformId();
    name = platformName;
  };

  protected Long getPlatformId(){
    return this.id;
  };

  protected String getPlatformName(){
    return this.name;
  }

  ....

}




package com.dragon.dictionary.salesforce;

import com.dragon.dictionary.Platform;

public class SalesforcePlatform extends Platform{

  // prevent instantiation
  private SalesforcePlatform() {
    super("salesforce");
  }

  private SalesforcePlatform(Long platformId, String platformName) {
    super(platformId, platformName);
  }  

  public static SalesforcePlatform getPlatformByName(String platformName){
    Platform platform = Platform.getPlatformByName(platformName);
    SalesforcePlatform salesforcePlatform = new SalesforcePlatform(platform.getPlatformId(), platform.getPlatformName());
    return salesforcePlatform;
  }
}

EDIT:

Thanks! So based on the responses, are you saying, this would have worked in the subclass:

  private SalesforcePlatform(Platform platform) {
    this.id = platform.getPlatformId();
    this.name = platform.getPlatformName();
  }

You are not calling the protected method from a sub-class, but from a static method. The fact that the static method is defined in the sub-class is irrelevant.

Edit:

Thanks! So based on the responses, are you saying, this would have worked in the sub class

That new updated code has two problems: - Your PlatForm class has no default constructor, so you need to call the super constructor and pass the arguments - The fields you are trying to assign are final. They will already be set by your super class constructor.

The rule says:

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

See here for the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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