流行编程语言的详细对比(7)--对象继承

对象继承

Java

public class Animal { 
    private String name;   
    private int id; 
    public Animal(String myName, String myid) { 
        //初始化属性值
    } 
    public void eat() {  //吃东西方法的具体实现  } 
    public void sleep() { //睡觉方法的具体实现  } 
} 
 
public class Penguin  extends  Animal{ 
}
public interface A {
    public void eat();
    public void sleep();
}
 
public interface B {
    public void show();
}
 
public class C implements A,B {
}

Js

//推荐寄生组合继承
function A() {  
        this.age=10;  
    }  
    A.prototype.name="jack";  
    function B() {  
        A.apply(this);//继承A的自身属性  
        this.sex="remale";  
    }  
    B.prototype = Object.create(A.prototype);//很关键,创建空对象继承父类的原型,保证不对父类进行修改  
    //B.prototype = A.prototype;//千万不能这样写,这样写会改变父类原型上的属性的值。  
    B.prototype.constructor = B;//这句话对结构没有什么影响,只是为了继承后结构的一致性,不然construtor指向A。  
    var b = new B();  
    alert("A的原型上的属性:"+b.name);  
    alert("A的自身属性:"+b.age);  
    alert("B的自身属性:"+b.sex);

ES6

class Person{
    constructor(skin,language){
        this.skin=skin;
        this.language=language;
    }
    say(){
        console.log('I am a Person')
    }
}
class Chinese extends Person{
    constructor(skin,language,positon){
        //console.log(this);//在没有调用super之前输出this会报错
        super(skin,language);
        //super();//不给父类构造函数传参,父类的构造数的值为undefined
        console.log(this);
        this.positon=positon;
    }
    aboutMe(){
        console.log(this.x+' '+this.y+' '+this.positon);
    }
}
let chinese =new Chinese('yellow','chinese','changsha');
chinese.say();//I am a Person
chinese.chinesesay();//I am a Person   I am a Chinese

Python

class Parent:        # 定义父类
   parentAttr = 100
   def __init__(self):
      print "调用父类构造函数"
   def parentMethod(self):
      print '调用父类方法'
   def setAttr(self, attr):
      Parent.parentAttr = attr
   def getAttr(self):
      print "父类属性 :", Parent.parentAttr
class Child(Parent): # 定义子类
   def __init__(self):
   	print "调用子类构造方法"
   def childMethod(self):
    print '调用子类方法 child method'
	c = Child()          # 实例化子类
	c.childMethod()      # 调用子类的方法
	c.parentMethod()     # 调用父类方法
	c.setAttr(200)       # 再次调用父类的方法
	c.getAttr()          # 再次调用父类的方法
#多重继承
class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite

Go

/*(1)struct
当匿名字段是一个struct的时候,那么这个struct所拥有的全部字段都被隐式地引入了当前定义的这个struct。
让我们来看一个例子,让上面说的这些更具体化*/
package main
import "fmt"
type Human struct {
	name string
	age int
	weight int
}
type Student struct {
	Human // 匿名字段,那么默认Student就包含了Human的所有字段
	speciality string
}

//(2) 对象方法
func (b *Box) SetColor(c Color) {
	b.color = c
}
func (b Box) SetColor(c Color) {
	b.color = c
}
//两者效果一致

//(3)对象interface
package main
import "fmt"
type Human struct {
	name string
	age int
	phone string
}
type Student struct {
	Human //匿名字段
	school string
	loan float32
}
type Employee struct {
	Human //匿名字段
	company string
	money float32
}
//Human实现Sayhi方法
func (h Human) SayHi() {
	fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
//Human实现Sing方法
func (h Human) Sing(lyrics string) {
	fmt.Println("La la la la...", lyrics)
}
//Employee重载Human的SayHi方法
func (e Employee) SayHi() {
	fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,e.company, e.phone) //Yes you can split into 2 lines here.
}
// Interface Men被Human,Student和Employee实现
// 因为这三个类型都实现了这两个方法
type Men interface {
	SayHi()
	Sing(lyrics string)
}

func main() {
	mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00}
	paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
	sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
	Tom := Employee{Human{"Sam", 36, "444-222-XXX"}, "Things Ltd.", 5000}
	//定义Men类型的变量i
	var i Men
	//i能存储Student
	i = mike
	fmt.Println("This is Mike, a Student:")
	i.SayHi()
	i.Sing("November rain")
	//i也能存储Employee
	i = Tom
	fmt.Println("This is Tom, an Employee:")
	i.SayHi()
	i.Sing("Born to be wild")
	//定义了slice Men
	fmt.Println("Let's use a slice of Men and see what happens")
	x := make([]Men, 3)
	//T这三个都是不同类型的元素,但是他们实现了interface同一个接口
	x[0], x[1], x[2] = paul, sam, mike
	for _, value := range x{
	value.SayHi()
	}
}
/*
通过上面的代码,你会发现interface就是一组抽象方法的集合,它必须由其他非interface类型实现,而不能自我实现,通过interface实现了duck-typing:即当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子

嵌入interface
是io包下面的 io.ReadWriter ,他包含了io包下面的Reader和Writer两个interface。*/
// io.ReadWriter
type ReadWriter interface {
	Reader
	Writer
}

Scala

//Scala重写一个非抽象方法,必须用override修饰符。
class Person {
  var name = ""
  override def toString = getClass.getName + "[name=" + name + "]"
}

class Employee extends Person {
  var salary = 0.0
  override def toString = super.toString + "[salary=" + salary + "]"
}

object Test extends App {
  val fred = new Employee
  fred.name = "Fred"
  fred.salary = 50000
  println(fred)
}

**PHP**
```PHP
class Child extends Parent {
   // 代码部分
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值