无法在构造函数之外识别对象

时间:2019-07-14 20:21:41

标签: java

我正在尝试为我的对象创建一些方法,但是在构造函数的外部,该对象的名称无法识别该对象

public class Playlist extends SongRecord {
    final int maxSongs = 50;

    public Playlist() {
        SongRecord[] list = new SongRecord[maxSongs];


    }
    public int size(){
        return list.length();
    }
}

错误消息表明无法识别列表

2 个答案:

答案 0 :(得分:1)

只需将list移至类范围:

public class Playlist extends SongRecord { 
  final int maxSongs = 50;
  private SongRecord[] list;

  public Playlist() {
    list = new SongRecord[maxSongs];
  }

  public int size(){
    return list.length();
  }
}

答案 1 :(得分:1)

因为如果您想在需要将列表移至类范围的所有位置访问列表,则列表范围位于构造函数中

  public class Playlist extends SongRecord {
  final int maxSongs = 50;
  SongRecord[] list;

  public Playlist() {
     list = new SongRecord[maxSongs];


  }
  public int size(){
     return list.length();
  }
}