0
点赞
收藏
分享

微信扫一扫

【Kotlin】Kotlin笔记5-面向对象编程3(数据类,单例类)


Kotlin笔记5-面向对象编程3-数据类,单例类


3.3 面向对象编程3

  • 数据类

Java实现数据类

public class Cellphone {
String brand;
double price;

public Cellphone(String brand, double price){
this.brand = brand;
this.price = price;
}

@Override
public boolean equals(Object object){
return brand.hasCode() + (int) price;
}

@Override
public String toString(){
return "Cellphone(brand=" + brand + ", price=" + price + ")";
}
}

Kotlin数据类

data

data class Cellphone(val brand: String, val price: Double)
fun main() {
val cellphone = Cellphone("xiaomi", 4399.0)
val cellphone2 = Cellphone("xiaomi", 4399.0)
println(cellphone)
println("cellphone equals cellphone2 " + (cellphone == cellphone2))
}

【Kotlin】Kotlin笔记5-面向对象编程3(数据类,单例类)_kotlin

  • 单例类

常见Java写法

class Singleton {
private static Singleton instance;

private Singleton(){}

public synchronized static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}

public void singletonTest(){
System.out.println("singletonTest is called");
}
}

​调用:​

Singleton singleton = Singleton.getInstance();
singleton.singletonTest();

Kotlin单例类

object

object Singleton {
fun singletonTest() {
println("singletonTest is called.")
}
}

​调用:​

Singleton.singletonTest()


举报

相关推荐

0 条评论