【问题标题】:How to access a method from another class without using extends keyword?如何在不使用扩展关键字的情况下从另一个类访问方法?
【发布时间】:2017-11-14 08:30:23
【问题描述】:

我有一个主类,然后是两个子类。

如下

public class Guitar  {

   public static void main(String argd[]) {
       Artist output = new Artist();
       output.perfomance();
   }
}

  class Artist  {
    String Name;
    void perfomance () {

    }

  }

  class Album {

  }

是否可以从 Artist 类调用性能方法并在 Album 类中使用它而不使用 extends 关键字?

【问题讨论】:

  • 有几种方法,取决于你在概念上真正想要实现的目标。
  • @kryger 。可以说我有那个方法的局部变量?
  • @procrastinator 。我创建了一个方法并从艺术家类中调用了该方法。 void perfomance () { Artist.perfomance();} 。但这并没有给出结果
  • @procrastinator .. 现在很好 .. 谢谢你

标签: java oop methods


【解决方案1】:

您可以使用组合而不是继承。

如果专辑扩展了艺术家,那么您建议使用专辑 IS-A 艺术家。 但是,如果一个专辑有一个艺术家作为成员,那么专辑就有一个艺术家。

IS-A vs HAS-A

所以一种方法可能是做

class Album {
  Artist artist;

  Album(Artist artist) {
    this.artist = artist;
  }

  void playLive() {
    artist.performance();
  }
}

所以打电话给你可能会这样做

public class Guitar  {

  public static void main(String[] args) {
     Artist prince = new Artist();
     Album purpleRain = new Album(prince);
     purpleRain.playLive();
  }
}

【讨论】:

  • 我不确定是否在这里使用构造函数,所以只是为了说明我的理解:如果没有构造函数,它会不会更容易和访问?
  • 如果没有艺术家的专辑是不可能的,那么这可以确保在实例化专辑时必须提供艺术家。如果您在调用 playLive() 方法之前没有提供艺术家,那么您将获得空指针异常。如果您要在 Album 类中实例化 Artist,那么您仍然需要弄清楚要使用的 Artist。另一种方法是将艺术家传递给 playLive 方法,不同的艺术家可以播放同一张专辑void playLive(Artist artist) 这完全取决于您尝试建模的业务逻辑。
  • 哦,是的。现在有道理了。 :)
  • @Spangen .. 在这里。在 main 方法中,我需要创建多少个对象才能调用它们
  • @coffemug 我会用一个例子来修改我的答案
【解决方案2】:

方法一Use composition

从构造器传递 Artist 对象

class Album {
  Artist artist;

  Album(Artist artist) {
    this.artist = artist;
  }

  void doSothing() {
    artist.performance();
  }
}

使用 set Method 设置 Artist 对象

class Album {
      Artist artist;
      void setArtist(Artist artist){ 
         this.artist = artist;
       }
      void doSothing(Artist artist) {
        artist.performance();
      }
    }

从方法中传递 Artist 对象

class Album {
      Artist artist;

      void doSothing(Artist artist) {
        artist.performance();
      }
    }

方法二:使函数性能static

 public class Artist  {
    String Name;
    static void perfomance () {
    }
  }
  class Album {
   void doSothing() {
     Artist.performance();
   }
  }

【讨论】:

  • 我喜欢这个答案,但现在我将 spangen 作为最佳答案 .. 谢谢你的回答
猜你喜欢
  • 2010-12-15
  • 2013-09-02
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多