contents of a null object
Hello
what are the contents of a null object?
e.g. if this is an object Employee
Code:
import java.io.*;
import java.util.*;
public class Employee implements Serializable {
private int employeeNumber;
private String employeeName;
Employee(int num, String name) {
employeeNumber = num;
employeeName= name;
}
public int getEmployeeNumber() {
return employeeNumber ;
}
public void setEmployeeNumber(int num) {
employeeNumber = num;
}
public String getEmployeeName() {
return employeeName ;
}
public void setEmployeeName(String name) {
employeeName = name;
}
}
then what would be the contents of getEmployeeName e.g. ?
Re: contents of a null object
That's like asking what's inside of nothing. If the object is null, how can there be any thing in it?
-tg
Re: contents of a null object
does that mean, that the employee null object does not even contain any of the methods or functions which it's class has?
Re: contents of a null object
It contains nothing. Hence it is null. Think of it like this. You have declared your variable with the intention of placing a reference to an object of type Employee in it. Until you do that, the variable contains no reference, hence it is null. It points to nothing. If you try using it I believe you get a NullPointerException ;)
Re: contents of a null object
There is no such thing as a null object. null is only a reference value.
Remember: except for primitives, all variables in Java are references. The objects are created on the heap by new, and then you assign the resulting reference to one of your reference variables. The variable then points to the object.
A variable that is null does not point to any object. Hence, talking about properties of "that object" is not meaningful.
Re: contents of a null object
thanks for the replies
why not leave the variable uninitialised?
is a reference to an object of type Employee the same as pointer(i knwo jaav does not have pointers) to an object of type Employee
Re: contents of a null object
If Java doesn't have pointers, how can anything be the same as them?
Java's references lie somewhere midway between references and pointers of C++: they can be null, unlike C++ references, but you can't do arithmetic on them or any of the funky things you can do with C++ pointers.
Variables aren't left uninitialized in Java because it's unsafe. If a reference is null, that's easily detectable and thus dereferencing can throw a NullPointerException. If it's uninitialized, how do you detect that?
That's why the compiler does flow analysis to make sure you never read from an uninitialized reference.
Re: contents of a null object
thanks for the reply,
i have done a bit of c++ programming, so that is where i was getting confused.
so no pointer arithmetic in java!
dont know what flow analysis is, but thanks for the insight.
Re: contents of a null object
Flow analysis is when the compiler tries to find out which code can be reached under which circumstances. Or at all.