1, the code is as follows:
[Java] View plain copy print? package com.yy.oop /** * associated class and associated objects * class Student is the companion of the associated object object student * object student is the companion object of the associated class class student */ //Associated class Class student (Var name:string,var address:string) { private var phone= " " //directly accesses the private members of the associated object def infocompobj () = println (" Companion object in companion class: " + student.sno" } //Companion object object student { private var sno:int = 100 def incrementsno () ={ sno += 1 //Plus 1 sno //return sno } def main (args: array[string)): Unit = { println ("Single Case object: " + student.incrementsno ()) //single Case object //instantiate associated class val obj = new student ("yy", "BJ") obj.infocompobj (); } }
2. The results are as follows
[plain] view plain copy print? Single Case object: 101 Associated Class Access companion object: 101
3. Scala apply
[Java] view plain copy print? Package Com.yy.oop/** * Companion Class and companion Object * Class student is the companion of object student associated class * Object student is associated with class student //Companion Class Student (var Name:string,var address:string) {private var phone= "110"///Direct access to associated objects Private member Def infocompobj () = println ("Access companion object in companion class: + Student.sno)}"