首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中使用self(php) like关键字?

如何在java中使用self(php) like关键字?
EN

Stack Overflow用户
提问于 2015-03-10 09:19:24
回答 2查看 802关注 0票数 2

我不知道java在php中没有像self这样的关键字来获得与这个php代码相同的结果。

代码语言:javascript
复制
    <?php
   class Person {
    private $name;

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

    public function getName() {
        return $this->name;
    }

    public function getTitle() {
        return $this->getName()." the programmer";
    }

    public function sayHello() {
        echo "Hello, I'm ".$this->getTitle()."<br/>";
    }

    public function sayGoodbye() {
        echo "Goodbye from ".self::getTitle()."<br/>";  
    }
}

class Geek extends Person {
    public function __construct($name) {
        parent::__construct($name);  //calling person class's constructor
    }

    public function getTitle() {
        return $this->getName()." the geek";
    }
}

$geekObj = new Geek("Avnish alok");
$geekObj->sayHello();
$geekObj->sayGoodbye();

/*This will output:

    Hello, I'm Avnish alok the geek
    Goodbye from Avnish alok the programmer
    */


?>

在java中,我编写了相同的代码,但结果不同。看看这里的java代码

代码语言:javascript
复制
    class Person {
    private String name;

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

    public String getName() {
        return this.name;
    }

    public String getTitle() {
        return this.getName()+" the programmer";
    }

    public void sayHello() {
        System.out.println("Hello, I'm "+this.getTitle());
    }

    public void sayGoodbye() {
        System.out.println("Goodbye from "+getTitle());  
        /*
      Here i'm unable to call Person class getTitle(). while in php i can easily achieve this by using self::getTitle().
    */
    }
}

class Geek extends Person {
    Geek(String name) {
        super(name);  
    }

    public String getTitle() {
        return this.getName()+" the geek";
    }
}

class This_Ex
{

public static void main(String[] arg)
{
Geek obj=new Geek("Avnish alok");
obj.sayHello();
obj.sayGoodbye();
}

}


/*This will output:

Hello, I'm Avnish alok the geek
Goodbye from Avnish alok the geek
*/

查看我的Person类sayGoodbye()方法

代码语言:javascript
复制
System.out.println("Goodbye from "+getTitle());  

这里我只想使用Person类的getTitle()方法。任何帮助都是非常感谢的。

EN

回答 2

Stack Overflow用户

发布于 2015-03-10 09:32:38

不,据我所知你不能这么做。如果您想要调用一个亲自指定的方法,您应该声明它是私有的,并亲自调用它。这样它就不能被覆盖了。如果您希望它可以从人的外部调用,但不想被覆盖,您可以声明它是最终的。无论哪种方式,您都需要一个单独的方法。

干杯,马库斯

票数 1
EN

Stack Overflow用户

发布于 2015-03-10 09:56:41

在Java中没有类似于self的内容。如果方法在子类中被重写,并且使用子类实例调用该方法,则将执行子类中的重写方法。

子类可以使用超级调用超类方法,在您的示例中,子类getTitle()方法可以是:

代码语言:javascript
复制
public String getTitle() {
    return super.getTitle() + " the geek";
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28959906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档