这段代码片段在Go中应该如何?当未定义子类时,如何从父类访问子类的方法?
class Parent {
abstract class MyParent {
abstract function doSomething();
function internal() {
return static::doSomething();
}
}
class MyChild extends MyParent {
function doSomething() {
return 'Test';
}
}
答案 0 :(得分:3)
正如@icza所说,Go中没有继承(这是一个最佳点)。最接近的是嵌入父类型。
type Parent struct {}
func (p *Parent) doSomething() {
fmt.Println("Test")
}
type MyChild struct {
Parent
}
func main() {
child := &MyChild{}
child.doSomething() // print "Test"
}
答案 1 :(得分:0)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body> <pre>
UserName : <input type="text" name=uname>
Password : <input type="password" name=upwd>
Confirm Password : <input type="password" name=cpwd>
Network : <select>
<option value="N1">Network1</option>
<option value="N2">Network2</option>
<option value="N3">Network3</option>
</select>
IP address : <input type="text" name=ipaddress>
</pre>
</body>
</html>
答案 2 :(得分:0)
我相信你最终想要完成的事情类似于&#34;模板方法&#34;设计模式:
在软件工程中,模板方法模式是一种行为 设计模式,定义一个算法的程序骨架 方法,称为模板方法,它将一些步骤推迟到子类。
https://en.wikipedia.org/wiki/Template_method_pattern
AFAIK,在Go中实现类似内容的唯一正确方法是使用@ pie-o-pah和@icza所说的接口。我说&#34;类似&#34;,因为你不能用接口定义方法作为接收器(即Go中没有部分抽象类型的东西)。
正确的实现如下:
package main
import "fmt"
// --------------------------
// define your purely abstract type as an interface
type MyParent interface {
doSomething() string
}
// define a function (your template method) which operates
// on that interface; an interface cannot be a function receiver,
// but it can always be a parameter
func internal(m MyParent) string {
return m.doSomething()
}
// define the implementation
type MyChild struct {}
// implement the methods for the interface
func (m *MyChild) doSomething() string {
return "Test"
}
// in Go any type which implements all methods in a given interface
// implements that interface implicitly, but you can "force" the
// compiler to check that for you using the following trick
// (basically try to assign a an instance of the interface to a variable,
// then discard it)
var _ MyParent = (*MyChild)(nil)
// -------------------------------
// test code
func main() {
m := &MyChild{}
fmt.Println(m.doSomething())
fmt.Println(internal(m))
}