|
Posted by Oli Filth on 10/13/75 11:30
Dikkie Dik said the following on 27/10/2005 23:20:
> Daedalus.OS wrote:
>
>> And even with, for example, the Math class (static class), would the
>> right way to go would be to create a normal class with static
>> funtions and a private constructor (since there can be no instance of
>> that class) rather than using an abstract class with static functions ?
>
>
> The PHP help does not say anything about private constructors. I guess
> it is a java thing to make them private to disallow instantiation.
Not just a Java thing.
> If you think about it, it is quite odd. The constructor is never called
> directly, but it is a language construction. You give a "new" keyword,
> some space in memory is reserved, the class name is attached to it as a
> type, and its constructor is called. By whom? By the virtual machine
> itself, basically.
> Making it private is _really_ odd.
Actually, it's a *very* common design pattern in many OO languages.
> It is not very consequent either. "private" in java means "visible only
> within the same instance". Only for constructors it suddenly means
> "visible within the same class".
Not true. "Private" means visible within the same class, e.g.:
class Foo
{
private $v;
function bar($theFoo)
{
echo $theFoo->$v;
}
}
$a = new Foo;
$b = new Foo;
$b->bar($a);
The equivalent works in Java, C++ and C#.
> Declaring it abstract will certainly stop instantiation. However,
> "abstract", communicates that it is meant as a superclass. I would not
> create a constructor at all and not declare it abstract either. As the
> static operator differs from the normal method calling, it is clear
> enough that instantiation is pointless. Any instance does not have
> properties or methods that can be called on it.
One of the ideas of writing good OO code is to explicitly enforce a
well-defined interface on your classes' users, i.e. what they can and
can't do with it. If you don't want them to be able to instantiate a
Foo, enforce it with a private constructor, don't leave it to chance.
Another example would be, if it makes no semantic sense for a Foo to
ever be extended, explicitly say so with the "final" keyword.
--
Oli
Navigation:
[Reply to this message]
|