Skip to content

Difference of constructor in PHP and Java

March 24, 2010
I know it’s lampzone, but I would like to talk about a little bit Java here.
In php , child’s constructor never calls parent’s constructor unless you call it intentionally. Like the code below, unless you uncomment out parent::__constuct() , it only prints out “I am B”.
<?php

// testab.php
class A {
public function __construct()
{
echo " I am A\n";
}
}
class B extends A {
public function __construct()
{
echo " I am B\n";
//parent::__construct();
}
}
$b = new B();
However, java does the contrary. If a child’s constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. By the way, you also HAVE TO call superclass constructor at the beginning of subclass constructor.
public class ConstructorTest {
    public static void main( String[] args )
    {
        //System.out.println("Hello world");
        //Parent p = new Parent();
        Child c = new Child();
    }
}

class Parent {

    public Parent( int n )
    {
        System.out.println("I'm a parent" + n);
    }
}

class Child extends Parent
{
    public Child()
    {
        super(10);
        System.out.println("I'm a child");
    }
}
Advertisements

From → java, php

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: