ULE$.sayHello();
}
public static void name_$eq(final String x$1) {
Student2$.MODULE$.name_$eq(var0);
}
public static String name() {
return Student2$.MODULE$.name();
}
public static void id_$eq(final int x$1) {
Student2$.MODULE$.id_$eq(var0);
}
public static int id() {
return Student2$.MODULE$.id();
}
}
伴生类和伴生对象
条件 1:在同一个源文件中, 条件 2:对象名和类名相同
//类名和object的名称一致
//类是对象的伴生类
//对象是类的伴生对象
class Demo6(val name: String) {
}
object Demo6 {
}
条件 2:伴生对象和伴生类之间可以互相访问彼此的私有属性和私有方法
package com.doit.day01.day02
/**
* 伴生对象的用途:
* 1.可以将静态的成员变量和普通成员变量分别声明
* 2.伴生对象自己内部定义了一个apply方法,可以简化创建对象(类的实例构造)
* 3.伴生对象自己定义了一个unapply方法,可以用于模式匹配
*/
class Car(var brand: String, var price: Double) {
def sayHello(): Unit ={
println("hello")
}
private val color: String = Car.color
Car.start()
}
object Car {
var color :String = "red"
def start(): Unit ={
println("汽车启动了,嗡~~~~~~~~")
}
}
object Demo02_伴生对象 {
def main(args: Array[String]): Unit = {
val car: Car = new Car("华为", 9.9)
println(car.brand)
println(car.price)
car.sayHello()
Car.start()
}
}
伴生对象的底层原理:
//decompiled from Car.class
package com.doit.day01.day02;
import scala.Predef.;
import scala.reflect.ScalaSignature;
@ScalaSignature(
bytes = "\u0006\u0001E3A\u0001E\t\u00015!A\u0011\u0005\u0001BA\u0002\u0013\u0005!\u0005\u0003\u0005/\u0001\t\u0005\r\u0011\"\u00010\u0011!)\u0004A!A!B\u0013\u0019\u0003\u0002\u0003\u001c\u0001\u0005\u0003\u0007I\u0011A\u001c\t\u0011m\u0002!\u00111A\u0005\u0002qB\u0001B\u0010\u0001\u0003\u0002\u0003\u0006K\u0001\u000f\u0005\u0006\u007f\u0001!\t\u0001\u0011\u0005\u0006\u000b\u0002!\tAR\u0004\u0006\u000fFA\t\u0001\u0013\u0004\u0006!EA\t!\u0013\u0005\u0006\u007f)!\tA\u0013\u0005\b\u0017*\u0001\r\u0011\"\u0001#\u0011\u001da%\u00021A\u0005\u00025Caa\u0014\u0006!B\u0013\u0019\u0003\"\u0002)\u000b\t\u00031%aA\"be*\u0011!cE\u0001\u0006I\u0006L\bG\r\u0006\u0003)U\tQ\u0001Z1zaER!AF\f\u0002\t\u0011|\u0017\u000e\u001e\u0006\u00021\u0005\u00191m\\7\u0004\u0001M\u0011\u0001a\u0007\t\u00039}i\u0011!\b\u0006\u0002=\u0005)1oY1mC&\u0011\u0001%\b\u0002\u0007\u0003:L(+\u001a4\u0002\u000b\t\u0014\u0018M\u001c3\u0016\u0003\r\u0002\"\u0001J\u0016\u000f\u0005\u0015J\u0003C\u0001\u0014\u001e\u001b\u00059#B\u0001\u0015\u001a\u0003\u0019a$o\\8u}%\u0011!&H\u0001\u0007!J,G-\u001a4\n\u00051j#AB*ue&twM\u0003\u0002+;\u0005I!M]1oI~#S-\u001d\u000b\u0003aM\u0002\"\u0001H\u0019\n\u0005Ij\"\u0001B+oSRDq\u0001\u000e\u0002\u0002\u0002\u0003\u00071%A\u0002yIE\naA\u0019:b]\u0012\u0004\u0013!\u00029sS\u000e,W#\u0001\u001d\u0011\u0005qI\u0014B\u0001\u001e\u001e\u0005\u0019!u.\u001e2mK\u0006I\u0001O]5dK~#S-\u001d\u000b\u0003auBq\u0001N\u0003\u0002\u0002\u0003\u0007\u0001(\u0001\u0004qe&\u001cW\rI\u0001\u0007y%t\u0017\u000e\u001e \u0015\u0007\u0005\u001bE\t\u0005\u0002C\u00015\t\u0011\u0003C\u0003\"\u000f\u0001\u00071\u0005C\u00037\u000f\u0001\u0007\u0001(\u0001\u0005tCfDU\r\u001c7p)\u0005\u0001\u0014aA\"beB\u0011!IC\n\u0003\u0015m!\u0012\u0001S\u0001\u0006G>dwN]\u0001\nG>dwN]0%KF$\"\u0001\r(\t\u000fQ