doufei5315 2011-04-17 03:44
浏览 51

将PHP转换为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 new project I'm getting assigned to.

  • 写回答

3条回答 默认 最新

  • duanhe1965 2011-04-17 03:47
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上