内容简介:面向对象的扩展可以通过
面向对象的扩展可以通过 继承 和 复合 来实现,但 Go 并不支持继承
class Pet { public void speak() { System.out.println("Pet Speak"); } } class Dog extends Pet { @Override public void speak() { System.out.println("Dog Speak"); } }
public class InheritTest { @Test public void subClassAccessTest() { Pet dog = new Dog(); dog.speak(); // Dog Speak } @Test // LSP : Liskov substitution principle // 里氏替换原则:派生类(子类)对象可以在程式中代替其基类(超类)对象 public void lspTest() { makePetSpeak(new Dog()); // Dog Speak } private void makePetSpeak(Pet pet) { pet.speak(); } }
Go的扩展
复合
type Pet struct { } func (p *Pet) speak() { fmt.Println("Pet Speak") } type Dog struct { // 复合:通过Pet扩展Dog的功能 p *Pet } func (d *Dog) speak() { d.p.speak() fmt.Println("Dog Speak") } func TestComplex(t *testing.T) { t.Logf("%T", Dog{}) // extension.Dog t.Logf("%T", &Dog{}) // *extension.Dog t.Logf("%T", new(Dog)) // *extension.Dog dog := new(Dog) dog.speak() // 输出 // Pet Speak // Dog Speak }
匿名嵌套类型
type Pet struct { } func (p *Pet) speak() { fmt.Println("Pet Speak") } func (p *Pet) eat() { fmt.Println("Pet Eat") } type Dog struct { // 匿名嵌套类型,不能当成继承使用 Pet } func (d *Dog) speak() { fmt.Println("Dog Speak") } func TestAnonymousNestedType(t *testing.T) { dog := new(Dog) dog.eat() // Pet Eat dog.speak() // Dog Speak } func TestNotInherit(t *testing.T) { // 不符合LSP // var d1 Pet = new(Dog) // cannot use new(Dog) (type *Dog) as type Pet in assignment // var d2 Pet = Dog{} // cannot use Dog literal (type Dog) as type Pet in assignment // var d3 Pet = (*Pet)(new(Dog)) // cannot convert new(Dog) (type *Dog) to type *Pet }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 【php 扩展开发】扩展生成器
- 喧喧发布 1.6.0 版本,扩展机制增强,支持服务器扩展
- 为vscode编写扩展
- JavaScript——DOM扩展
- Mac内核扩展开发
- VisualStudio 扩展开发
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Art of Computer Programming, Volumes 1-3 Boxed Set
Donald E. Knuth / Addison-Wesley Professional / 1998-10-15 / USD 199.99
This multivolume work is widely recognized as the definitive description of classical computer science. The first three volumes have for decades been an invaluable resource in programming theory and p......一起来看看 《The Art of Computer Programming, Volumes 1-3 Boxed Set》 这本书的介绍吧!