OneMoreVladimir
OneMoreVladimir

Reputation: 1673

Class reference in Java

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;
    }
    public void bark() {
        System.out.println("I am barking!!!");
    }
}

Upvotes: 1

Views: 231

Answers (7)

Peter Lawrey
Peter Lawrey

Reputation: 533492

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.

Upvotes: 1

Eser Aygün
Eser Aygün

Reputation: 8004

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

Upvotes: 2

Hyperboreus
Hyperboreus

Reputation: 32429

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?

Upvotes: 2

melhosseiny
melhosseiny

Reputation: 10144

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

Upvotes: 2

RMT
RMT

Reputation: 7070

Dog fellow = null;

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

Upvotes: 2

McDowell
McDowell

Reputation: 108879

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

Upvotes: 5

Miki
Miki

Reputation: 7188

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

Upvotes: 5

Related Questions