流行编程语言的详细对比(6)--对象建立和析构函数

来源:互联网 发布:魔女的条件知乎 编辑:程序博客网 时间:2024/06/05 10:17

对象建立

Java
(1)使用new关键字,调用了构造函数

Employee emp1 = new Employee();

(2)使用Class类的newInstance方法,调用了构造函数

Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();或者Employee emp2 = Employee.class.newInstance();

(3)使用Constructor类的newInstance方法,调用了构造函数
和Class类的newInstance方法很像,
java.lang.reflect.Constructor类里也有一个newInstance方法可以创建对象。
我们可以通过这个newInstance方法调用有参数的和私有的构造函数。

Constructor<Employee> constructor = Employee.class.getConstructor();Employee emp3 = constructor.newInstance();

(4)使用clone方法

Employee emp4 = (Employee) emp3.clone();

(5)使用反序列化

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));Employee emp5 = (Employee) in.readObject();

Js
(1)原始方式

var oCar = new Object;oCar.color = "blue";oCar.showColor = function() {  alert(this.color);};

(2)工厂方式

function createCar() {  var oTempCar = new Object;  oTempCar.color = "blue";  oTempCar.showColor = function() {    alert(this.color);  };  return oTempCar;}var oCar1 = createCar();

(3)构造函数方式

function Car(sColor,iDoors,iMpg) {  this.color = sColor;  this.showColor = function() {    alert(this.color);  };}var oCar1 = new Car("red",4,23);

(4)原型方式

function Car() {}Car.prototype.color = "blue";Car.prototype.showColor = function() {  alert(this.color);};var oCar1 = new Car();

(5)混合的构造函数,原型方式推荐

function Car(sColor) {  this.color = sColor;}Car.prototype.showColor = function() {  alert(this.color);};var oCar1 = new Car("red");

(6)动态原型,推荐

function Parent(){    this.name="李小龙";     if(typeof Parent._lev=="undefined"){            Parent.prototype.lev=function(){                 return this.name;       }   }    };      var  x =new  Parent(); 

Python

class Employee:   '所有员工的基类'   empCount = 0   def __init__(self, name, salary):      self.name = name      self.salary = salary      Employee.empCount += 1   def displayCount(self):     print "Total Employee %d" % Employee.empCount   def displayEmployee(self):      print "Name : ", self.name,  ", Salary: ", self.salary"创建 Employee 类的第一个对象"emp1 = Employee("Zara", 2000)"创建 Employee 类的第二个对象"emp2 = Employee("Manni", 5000)emp1.displayEmployee()emp2.displayEmployee()print "Total Employee %d" % Employee.empCount

Go
golang 中有两个内存分配机制 :new和make,二者有明显区别.

new:用来初始化一个对象,并且返回该对象的首地址.其自身是一个指针.可用于初始化任何类型

make:返回一个初始化的实例,返回的是一个实例,而不是指针,其只能用来初始化:slice,map和channel三种类型

package main  import (      "fmt"  )  func main() {      a := new([]int)      fmt.Println(a)     //输出&[],a本身是一个地址      b := make([]int, 1)      fmt.Println(b)     //输出[0],b本身是一个slice对象,其内容默认为0  }  

通过这个例子可以看出,当对slice,map以及channel进行初始化时,使用make比new方式要好,而其他形式的则利用new进行初始化.

初始化:

使用new进行初始化时只能是默认初始化,无法赋值.很多时候,默认初始化并不是一个好主意,例如一个结构体,默认值的结构体初始化并没有多大用处,所以面对结构体初始化我们一般适用如下方式:

type Rect struct {  x, y float64  width, height float64  }  

所以我们通过在结构体前面添加取地址符号&对该结构体进行初始化:

rect3 := &Rect{0, 0, 100, 200}    rect4 := &Rect{width: 100, height: 200}  

这种初始化方式在golang中初始化结构体是十分常见的.

Scala

import java.io._class Point(xc: Int, yc: Int) {   var x: Int = xc   var y: Int = yc   def move(dx: Int, dy: Int) {      x = x + dx      y = y + dy      println ("x 的坐标点: " + x);      println ("y 的坐标点: " + y);   }}object Test {   def main(args: Array[String]) {      val pt = new Point(10, 20);      // 移到一个新的位置      pt.move(10, 10);   }}

PHP

class Site {  /* 成员变量 */  var $url;  var $title;  /* 成员函数 */  function setUrl($par){     $this->url = $par;  }  function getUrl(){     echo $this->url . PHP_EOL;  }  function setTitle($par){     $this->title = $par;  }  function getTitle(){     echo $this->title . PHP_EOL;  }//构造函数function __construct( $par1, $par2 ) {   $this->url = $par1;   $this->title = $par2; }}$runoob = new Site;

析构函数

Java

protected void finalize(){    System.out.println("in finalize");}

在 Java 编程里面,一般不需要我们去写析构方法。

Js
Js没有析构函数

Python

#!/usr/bin/python# -*- coding: UTF-8 -*-class Point:   def __init__( self, x=0, y=0):      self.x = x      self.y = y   def __del__(self):      class_name = self.__class__.__name__      print class_name, "销毁"pt1 = Point()pt2 = pt1pt3 = pt1print id(pt1), id(pt2), id(pt3) # 打印对象的iddel pt1del pt2del pt3#以上实例运行结果如下:#3083401324 3083401324 3083401324#Point 销毁

Go
因为类型就是简单的结构体,所以类型并没有所谓的构造函数和析构函数

Scala
Scala无析构函数

PHP

<?phpclass MyDestructableClass {   function __construct() {       print "构造函数\n";       $this->name = "MyDestructableClass";   }   function __destruct() {       print "销毁 " . $this->name . "\n";   }}$obj = new MyDestructableClass();?>
阅读全文
0 0
原创粉丝点击