面向对象编程,但是静态变量school确是由类名调用的
初始scala
package chapter01
/*
object:关键字,声明一个单例对象(伴生对象)
*/
object HelloWorld {
/*
main方法,从外部可以直接调用执行的方法
def 方法名称(参数名称:参数类型):方法返回值类型={方法体}
*/
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();
}
}
引入伴生对象,与同名的class相伴相生,去除掉java中的static,school属性由student对象调用
class Student就相当于构造函数,def 自定义printInfo函数结构参照上面的结构介绍
main函数定义在object Student里面
scala:
package chapter01
class Student(name:String,age:Int) {
def printInfo():Unit={
println(name + " " + age + " " + Student.school);
}
}
//引入伴生对象
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()
}
}
|