当前位置:网站首页>Scala-day01- companion objects and HelloWorld

Scala-day01- companion objects and HelloWorld

2022-06-26 12:09:00 There will always be daylight

object-oriented programming , But static variables school Is actually called by the class name

initial scala

package chapter01

/*
  object: keyword , Declare a singleton object ( Companion )
 */
object HelloWorld {
  /*
    main Method , From the outside, you can directly call the executed method 
    def  Method name ( Parameter name : Parameter type ): Method return value type ={ Method body }
   */
  def main(args: Array[String]): Unit = {
    println("hello world")
    System.out.println("hello world")
  }
}

 java:

public class Student {

    private String name;
    private Integer age;
    private static String school = "atguigu";

    public Student(String name,Integer age){
        this.name = name;
        this.age = age;
    }

    public void printInfo(){
        System.out.println(this.name + " " + this.age + " " + Student.school);
    }

    public static void main(String[] args) {
        Student alice = new Student("alice", 20);
        Student bob = new Student("bob", 23);
        alice.printInfo();
        bob.printInfo();
    }

}

Introducing companion objects , With the same name class Accompany each other , Remove java Medium static,school Attribute from student Object call

class Student Is equivalent to a constructor ,def Customize printInfo Refer to the above structure for function structure

main Function defined in object Student Inside

scala:

package chapter01

class Student(name:String,age:Int) {

  def printInfo():Unit={
    println(name + " " + age + " " + Student.school);
  }

}

// Introducing companion objects 
object Student{
  val school:String = "atguigu"

  def main(args: Array[String]): Unit = {
    val alice = new Student("alice",20)
    val bob = new Student("bob",20)
    alice.printInfo()
    bob.printInfo()
  }
}

原网站

版权声明
本文为[There will always be daylight]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170527108275.html