Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

new物件的問題....

編譯器是JC....

/**

* @(#)p5.java

*

*

* @author

* @version 1.00 2007/11/13

*/

public class p5 {

/**

* Creates a new instance of <code>p5</code>.

*/

public p5() {

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

// TODO code application logic here

ooo p1;

p1=new ooo();

p1.setname("KEN");

System.out.println(p1.getname());

p1.setnickname("5544");

System.out.println(p1.getnickname());

}

public class ooo{

private String name;

private String nickname;

public void setname(String newname){

name=newname;

}

public ooo(){

}

public String getname(){

return name;

}

public void setnickname(String newnickname){

nickname=newnickname;

}

public String getnickname(){

return name;

}

}

}

結果都無法成功....會出現

non-static variable this cannot be referenced from a static context

能告訴我為什麼嗎??

Update:

這裡打錯......

public String getnickname(){

return nickname;

}

用netbean就可以為啥JC就有問題??

Update 2:

哇咧....可以了

可是我適用new的類別阿

為啥他要我用static

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    這原因很簡單

    public static void main(String[] args) {

    // TODO code application logic here

    ooo p1;

    p1=new ooo();

      ↑↑

    你在 static 的 method直接new p5的內部類別ooo!

    由於ooo不是static的內部匿名類別,你必須先有p5類別的實體才能建構ooo的實體

    所以你必須改成這樣

    ooo p1;

    p1 = new p5( ).new ooo( );

    不然就把內部類別改成靜態內部類別,那就不需要p5的實體了。

    2007-11-14 18:55:22 補充:

    呃,打太快,打錯了

    由於ooo不是static的內部匿名類別,改成

    「由於ooo不是static的內部類別」 才對

    剛剛邊打邊想到匿名內部類別,結果手就不聽使喚打上去了...Orz

    Source(s): My experience
  • Ashley
    Lv 7
    1 decade ago

    public static class ooo{

    這裡改 static 試試看

Still have questions? Get your answers by asking now.