2

I would like to ask if there is anyways in java to ensure that a class can never be instantiated as null. But i want to do this inside the class. For example

class A 
{
   I can never be null 
}

class B
{
  A a = null ; << No you cant. Does not compute :P
}

Thanks in advance.

4 Answers 4

8

This is not, generally speaking, possible. When you declare:

A a = null;
A a2 = new A();

Both a and a2 are references, not actual objects. Think of a reference as a pointer, but one that does not support C-style pointer arithmetic.

A a = null;

sets up a reference (a pointer) that can point to an object of type A, but is currently initialized to null. It's not possible to have class A ensure that there are never any null references to things of type A.

Sign up to request clarification or add additional context in comments.

Comments

7

No.

Comments

2

No. You cannot do that. What is your use case, maybe we can suggest an alternative.

2 Comments

A relevant to my case example: class A { int size; public A(){size = 0;} public void add(A a) {size = a.size + size;} } class B { A a = null; A aa = new A(); aa.add(a); } Hope it makes sense . i think is bad written comment :P
i was wondering if i can get compiler error at B , saying that A cannot be null. My case is class A , i wrote B just to show what shouldnt happen...
0

We often talk about a null object but that is totally misleading. An object is an object and only a variable can hold the value null (instead of a reference to an object).

Something like a null object simply doesn't exist in Java.

If we do a

A a = new A();

we create a new instance of A and store a reference (a pointer) to this instance at the variable. The variables value is now some sort of address of the location of this new object. If the instantiation fails (an exception is thrown) then no assignement will be made and the variable keeps its old value. Which may be null - but again, this just tells us that the variable doesn't hold a reference to any object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.