Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在不使用extends关键字的情况下从另一个类访问方法?_Java_Oop_Methods - Fatal编程技术网

Java 如何在不使用extends关键字的情况下从另一个类访问方法?

Java 如何在不使用extends关键字的情况下从另一个类访问方法?,java,oop,methods,Java,Oop,Methods,我有一个主课,后面是两个子课 如下 public class Guitar { public static void main(String argd[]) { Artist output = new Artist(); output.perfomance(); } } class Artist { String Name; void perfomance () { } } class Album {

我有一个主课,后面是两个子课

如下

public class Guitar  {

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

  class Artist  {
    String Name;
    void perfomance () {

    }

  }

  class Album {

  }

可以从Artister类调用方法performance并在Album类中使用它而不使用extends关键字吗

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

如果相册扩展了艺术家,那么您建议相册是艺术家。 然而,如果一张专辑有一位艺术家作为成员,那么专辑就有一位艺术家

因此,一种方法可能是

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();
  }
}

方法1

从constractor传递艺术家对象

class Album {
  Artist artist;

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

  void doSothing() {
    artist.performance();
  }
}
使用Set方法设置艺术家对象

class Album {
      Artist artist;
      void setArtist(Artist artist){ 
         this.artist = artist;
       }
      void doSothing(Artist artist) {
        artist.performance();
      }
    }
从方法传递艺术家对象

class Album {
      Artist artist;

      void doSothing(Artist artist) {
        artist.performance();
      }
    }
方法2:实现功能性能


有几种方法,这取决于你在概念上想要达到的目标。@kryger。让我们假设我有局部变量的方法?@拖延者。我创建了一个方法,并从artist类调用了该方法<代码>无效性能(){Artist.performance();}。但这并不是给人一个机会result@procrastinator .. 现在天气很好。。thank uI我不确定在这里使用构造函数,所以我只是想让我的理解更清楚:没有构造函数不是更容易访问吗?如果没有艺术家就没有相册,那么这确保了在实例化相册时必须提供艺术家。如果在调用
playLive()
方法之前没有提供艺术家,则会出现空指针异常。如果要在Album类中实例化艺术家,则仍然需要确定要使用的艺术家。另一种方法是将艺术家传递到playLive方法,不同的艺术家可以播放同一张专辑
void playLive(艺术家-艺术家)
这一切都取决于您尝试建模的业务逻辑。哦,是的。现在有意义了。:)@斯潘根。。在这里在main方法中,我需要创建多少个对象来调用每个them@coffemug我会用一个例子来修正我的答案我喜欢这个答案,但现在我给斯潘根作为最好的答案。。谢谢你的回答
 public class Artist  {
    String Name;
    static void perfomance () {
    }
  }
  class Album {
   void doSothing() {
     Artist.performance();
   }
  }