开发者

Class reference in Java

开发者 https://www.devze.com 2023-03-09 01:25 出处:网络
Hello Guys :D Why can\'t I execute the following code withoud getting a runtime exception? How should it be rewritten? I am migrating from C++ where I could easily do that I suppose :D.

Hello Guys :D Why can't I execute the following code withoud getting a runtime exception? How should it be rewritten? I am migrating from C++ where I could easily do that I suppose :D.

class MyJavaClass {
    public static void main(String args[]) {
        Dog bushui_RIP = new Dog();
        Dog fellow = null;
        bushui_RIP.bark(fellow);
        fellow.bark();
    }
}
class Dog {
    public void bark(Dog buddy) {
        buddy = this;
    }
    pu开发者_StackOverflow中文版blic void bark() {
        System.out.println("I am barking!!!");
    }
}


fellow is null, therefore there is no object that can bark.


Dog fellow is a reference variable, but it is passed by value to the method.


Dog fellow = null;

you gotta Initialise it before you can make your dogs bark.


Change Dog fellow = null; to Dog fellow = new Dog();.


The problem is your local variable fellow. It is null when you try to call bark() of it.

When you call bushui_RIP.bark(fellow) it is indeed a pass by reference, but the reference itself is passed as value (how else). So you assign to a local variable buddy in your bark(Dog) function without touching the original reference fellow.

What is bark(Dog) supposed to do? Clone this and return a new instance of Dog or assign this as it is to a reference?


In Java, you cannot pass object references by reference, as you do in C++ by writing Dog **ppDog. You can pass the value (this) to the caller as a return value or in a field.

Or, you can use "the cell pattern" as I call it. Firstly, define your Cell<T> class that holds a reference to an object with type T:

class Cell<T> {
    public T item;

    Cell(T item) {
        this.item = item;
    }
}

Then, you can write:

private void bark(Cell<Dog> buddy) {
    buddy.item = this;
}

...

Dog bushui_RIP = new Dog();
Cell<Dog> fellow = Cell(null);
bushui_RIP.bark(fellow);
fellow.item.bark();


Another soltuion is to change bark() to be static.

public static void bark() {
    System.out.println("I am barking!!!");
}

((Dog) null).bark();
// is the same as
Dog.bark();

I am migrating from C++ where I could easily do that I suppose

I didn't think you would easily de-reference a NULL pointer without gettting a segmentation fault which kills your application.

0

精彩评论

暂无评论...
验证码 换一张
取 消