在Groovy中,如何在扩展超类的类中重写超类中的方法?Java方式不起作用,因为两个方法(超类中的方法和子类中的方法)都在执行。例如:
class SuperClass {
SuperClass(){
println("This is the superclass")
}
def awaitServer(){
println("awaiting server in the superclass")
}
}
class SubClass extends SuperClass{
SubClass(){
println("This is the subclass")
}
@Override
def awaitServer(){
println("awaiting server in the subclass")
}
}
//////
SubClass sb = new SubClass()
sb.awaitServer()我得到的输出是:
awaiting server in the superclass
awaiting server in the subclass正如您所看到的,当我在子类中重写超类的方法时,这两个方法都会执行。为什么会发生这种情况?Groovy中的方法重写是如何实现的?
我已经在网上搜索过了,但我还是找不到。谁能提供一个样本或一个简单的例子?
先谢谢你,
发布于 2015-02-27 21:11:45
您忘记添加def。下面的代码可以正常工作:
class SuperClass {
SuperClass(){
println("This is the superclass")
}
def awaitServer() {
println("awaiting server in the superclass")
}
}
class SubClass extends SuperClass{
SubClass() {
println("This is the subclass")
}
@Override
def awaitServer() {
println("awaiting server in the subclass")
}
}
SubClass sb = new SubClass()
sb.awaitServer()它输出:
This is the superclass
This is the subclass
awaiting server in the subclass看看下面的输出:
[opal@opal-mac-2]/tmp % cat lol.groovy
class SuperClass {
SuperClass(){
println("This is the superclass")
}
def awaitServer() {
println("awaiting server in the superclass")
}
}
class SubClass extends SuperClass{
SubClass() {
println("This is the subclass")
}
@Override
def awaitServer() {
println("awaiting server in the subclass")
}
}
SubClass sb = new SubClass()
sb.awaitServer()
[opal@opal-mac-2]/tmp % groovy -v
Groovy Version: 2.4.0 JVM: 1.8.0_05 Vendor: Oracle Corporation OS: Mac OS X
[opal@opal-mac-2]/tmp % groovy lol.groovy
This is the superclass
This is the subclass
awaiting server in the subclass在groovy 1.8.6中:
[opal@opal-mac-2]/tmp % gvm use groovy 1.8.6
==== BROADCAST =================================================================
* 27/02/15: Springboot 1.1.11.RELEASE has been released on GVM. #spring
* 27/02/15: Springboot 1.2.2.RELEASE has been released on GVM. #spring
* 26/02/15: Grails 3.0.0.M2 has been released on GVM. #grailsframework
================================================================================
Stop! groovy 1.8.6 is not installed.
Do you want to install it now? (Y/n): Y
Downloading: groovy 1.8.6
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 15.5M 100 15.5M 0 0 2666k 0 0:00:05 0:00:05 --:--:-- 3716k
Installing: groovy 1.8.6
/Users/opal/.gvm/tmp/groovy-1.8.6 -> /Users/opal/.gvm/groovy/1.8.6
Done installing!
Using groovy version 1.8.6 in this shell.
[opal@opal-mac-2]/tmp % groovy lol.groovy
This is the superclass
This is the subclass
awaiting server in the subclasshttps://stackoverflow.com/questions/28765926
复制相似问题