Title: Converting PHP to Java
Tags: java;php;inheritance;constructor
Question: 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-&gt;_name = $name;
function showName()
echo "{$this-&gt;_name} is a cool guy";
class Bad extends Cool
function showName()
echo "{$this-&gt;_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 new project I'm getting assigned to.


Here is another answer: 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.

Here is another answer: 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

Here is another answer: 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

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2011:00:04/17/11', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><php><inheritance><constructor>', 'Title': 'Converting PHP to Java', 'ViewCount': 1506, 'id': 5691317, 'user_AboutMe': None, 'user_AccountId': 738130.0, 'user_DisplayName': 'Jhonatan', 'user_Reputation': 31.0, 'user_Views': 1.0, 'user_id': 711778.0}}