class CardBoard
{
Short story = 200;
CardBoard go(CardBoard cb)
{
cb = null;
return cb;
}
public static void main(String[] args)
{
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
// expecting null pointer exception
c1 = null;
// do stuff;
}
}
1169 次
7 に答える
1
public static void main(String[] args)
{
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2); // go method is returning 'null' so c3=null
// expecting null pointer exception
c1 = null;
c3.go(c2); // you will get NullPointerException here.
}
go()
でメソッドを呼び出すと、次のc3
ようになります。NullPointerException
に割り当てられている参照変数NullPointerException
のメソッドを呼び出すと、が取得されます。null
于 2013-03-22T12:51:20.277 に答える
1
例えば
Class Apple
{
void applePrint()
{
System.out.println("Apple");
}
}
Class Mango
{
void mangoPrint()
{
System.out.println("Mango");
}
}
コードのどこかで、そうしているとします。
Apple a;
Mango m;
この変数を使用しa
たりm
、クラス メンバーにアクセスしようとすると、
a.printApple(); or m.printMango();
NPEをスローします
つまり、クラスのオブジェクトへの参照変数を定義しますが、実際にはそれらを作成しません。
Apple a = new Apple();
Mango m = new Mango();
[私がJavaに慣れていないときにたくさんやった]
于 2013-03-22T12:26:06.290 に答える
1
NullPointerException は、何も指していない参照、つまり null を使用してメソッドまたは変数にアクセスしようとした場合にのみ発生します。
NullPointerException を取得するようにコードを変更しました。
class CardBoard {
Short story = 200;
CardBoard go(CardBoard cb) {
cb = null;
return cb;
}
public static void main(String[] args) {
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
// expecting null pointer exception
c1 = null;
// If you try to call a method or access any member variable with null reference you will get the exception
c3.story = 20; //NullPointerException will occur
// do stuff;
}
}
于 2013-03-22T12:22:48.473 に答える