I have a problem in understanding OOP…
This is it :
Sometime’s you create an object with this syntax:
Object ObjectName = new Object();
But sometimes, we don’t need to do that like in Android:
Textview TextviewName;
Or in J2ME:
form formName;
I already searched it and I got some information (but not sure) that this is because of static method… is it true? I think it has a relation with Polymorphism.. is it true?
Thanks all.
PS : Sory if I made some mistakes, English is not my native languange 😀
Forget static methods – they’re not relevant here. I’d advocate only looking at static methods / elements when you’ve truly grasped what objects are.
In Java, you can do this:
Just as well as you can do this:
In the first example, you’re creating a reference but you’re not populating that reference with anything, in the second example you’re creating a reference and populating it with a new object, on which you can call methods, modify values and so on.
If you try and call methods on the first declaration you won’t be able to – there’s nothing there. Depending on the language and how you’ve declared it this might produce an error at runtime or a compile time error (Java does both depending on whether it’s a field or a local variable.) The principle though is the same for all OO languages, you can’t dereference (call methods, fields, etc.) on a reference that hasn’t been populated, because in effect you’re trying to call a method on something that isn’t there.