java,c#,php类与继承简单比较

来源:互联网 发布:u盘提示格式化数据恢复 编辑:程序博客网 时间:2024/06/07 05:03

原文  http://www.cnblogs.com/qingjiao/p/4019720.html

简单比较 java,c#,php 创建类,继承,创建对象的异同点。

先简单用三种语言创建两个类Human,Singer,其中Singer继承Human。

相同点:

1可以使用继承,并且只能继承一个类,不能多重集成,但是接口可以多重继承其他接口。

2访问性,子类可以都可以访问父类的非私用属性和方法。

不同点:

1继承,java和php通过extends关键字表示继承,c#使用:表示;

2定义属性和方法,java和c#一样,php的属性和对象前都加上$字符前缀,如$name;使用function关键字定义方法;构造函数写法为:  function __construct

3对象访问属性和方法,java和c#完全一样,创建对象和调用示范:

Singer s = new Singer("dd",166,110);

s.eat("苹果");

php属性通过->符号访问。

$dd = new Singer("dd",166,110);

$dd->eat("橘子");

代码简单实现如下:

java代码:public class Human{  public string name;  public int height;  public int weight;  public void eat(string food)  {  system.out.println("eat"+food);  }}public class Singer extends Human{//1    public string songType;    public Singer(string name,int height,int weight){          this.name=name;          this.height = height;          this.weigh=weigh;   }      public void singAsong(string songName){      System.out.println("sing "+songName);   }}
c#代码:public class Human{  public string name;  public int height;  public int weight;  public void eat(string food)  {   Console.WriteLine("eat"+food);  }}public class Singer : Human{//1    public string songType;    public Singer(string name,int height,int weight){          this.name=name;          this.height = height;          this.weigh=weigh;   }   public void singAsong(string songName){      Console.WriteLine("sing "+songName);   }}
<?php  class Human{  public $name;  public $height;  public $weight;  public function eat($food)  {  echo $this->name." like eat".$food;  }} class Singer extends Human{//1    public  $songType;    function __construct($name,$height,$weight){          $this->name=$name;          $this->height = $height;          $this->weigh=$weigh;   }   public function singAsong($songName){      echo $this->name." is sing ".$songName;   }}?>

0 0
原创粉丝点击