开发者

Converting PHP to Java

I have worked with PHP for 6 years now and am certified in it, but lately I have decided that I should learn Java, as I worked a lot with the Zend framework, which is inspired by Java, but now I have what is, perhaps, a stupid problem with Java.

In PHP I would do this:

class Cool
{
    protected $_name;

    function __construct($name)
    {
        $this->_name = $name;
    }

    function showName()
    {
        echo "{$this->_name} is a cool guy";
    }
}

class Bad extends Cool
{
    function showName()
    {
        echo "{$this->_name} is a bad guy";
    }
}

$bad = new Bad("jhon");
// prints jhon is a bad guy

Since Java doesn't inherit constructors, what would be the best way to do something like this in Java? Will I have to think of a different type of patterns to solve this kind of thing?

I appreciate the help since I'm really new to Java and since I use this kind of thing a lot I'd like to know if there's any cool way to do it in Java. I need to use it on a n开发者_开发知识库ew project I'm getting assigned to.


In Java, you'll have to write a constructor for each class and call super() to use the parent's constructor. If you don't want to alter the constructor, all you need to do in the subclass constructor is call super().

In this case, Bad would look like this:

public class Bad extends Cool {
    public Bad(String name) {
        super(name);
    }
    // Any other additions
}


Constructors aren't inherited directly as members on the subclass, but any non-private constructors will be accessible via a corresponding super call from within the subclass, which works just as well. When you don't want to modify any behavior of the superclass's constructor, just add a version to your subclass that takes the same parameter(s) and calls the super version.

So you could write the above code in Java as:

public class Cool {
    protected String name;

    public Cool(String name){
        this.name = name;
    }

    public void showName() {
        System.out.println(this.name + " is a cool guy");
    }
}

public class Bad extends Cool {
    public Bad(String name){
        super(name);
    }

    @Override
    public void showName() {
        System.out.println(this.name + " is a bad guy");
    }
}

Cool bad = new Bad("jhon");
bad.showName(); // prints jhon is a bad guy


You are correct in that constructors are not inherited, you would need to do:

public class Bad extends Cool {
 public bClass( String name ) {
   super( name );
 }
}

This will call the supers constructor, which would be the parent's constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜