我不知道java在php中没有像self这样的关键字来获得与这个php代码相同的结果。
<?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代码
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()方法
System.out.println("Goodbye from "+getTitle()); 这里我只想使用Person类的getTitle()方法。任何帮助都是非常感谢的。
发布于 2015-03-10 09:32:38
不,据我所知你不能这么做。如果您想要调用一个亲自指定的方法,您应该声明它是私有的,并亲自调用它。这样它就不能被覆盖了。如果您希望它可以从人的外部调用,但不想被覆盖,您可以声明它是最终的。无论哪种方式,您都需要一个单独的方法。
干杯,马库斯
发布于 2015-03-10 09:56:41
在Java中没有类似于self的内容。如果方法在子类中被重写,并且使用子类实例调用该方法,则将执行子类中的重写方法。
子类可以使用超级调用超类方法,在您的示例中,子类getTitle()方法可以是:
public String getTitle() {
return super.getTitle() + " the geek";
}https://stackoverflow.com/questions/28959906
复制相似问题