/**
*创建一个类
* -1.属性field,attribute:名词
* -2.方法method/函数function:动词
*/
class People {
/**
* 属性定义
*/
//当属性使用var声明的时候,编译的时候,会生成Getter和setter方法
var name:String = _
//当属性使用val声明的时候,编译的时候,会生成Getter方法
val age:Int = 17
/**
* 方法定义
*/
def watchFootBall(teamName:String):Unit= {
println(s"$name is watching match of $teamName")
}
def sayHello(name:String):String = {
s"Hello $name"
}
}
测试
object SimpleObjectDemo {
def main(args: Array[String]): Unit = {
//创建一个对象
val people = new People()
//设置名称
people.name = "huadian"
//获取属性的值
println(s"name is ${people.name}")
println(s"age is ${people.age}")
people.watchFootBall("Chelse")
println(people.sayHello("lalal"))
}
}
object Demo01 {
def main(args: Array[String]): Unit = {
val p1: People = new People("lalal",18)
val p2: People = People("lalal",18,"HD")
println(p1.school)
println(p2.school)
val p3: People = People("ww",18)
println(p3.school)
println( People.getMoney())
}
}
接口的定义与实现
/**
* 定义一个Trait,用于实现 与 人打招呼
*
* 和Java中interface一样
*/
trait HelloTrait {
def sayHello(name:String)
}
/**
* 定义一个Trait,用于 交朋友
*/
trait MakeFriendsTrait {
def makeFriends(people:People)
}
class People(val name:String) extends HelloTrait with MakeFriendsTrait {
override def sayHello(name: String): Unit = {
println(s"Hello $name")
}
override def makeFriends(people: People): Unit = {
println(s"my name is $name ,you name is ${people.name}")
}
}
测试
object TraitDemo {
def main(args: Array[String]): Unit = {
val p1 = new People("lw")
val p2 = new People("Ll")
p1.sayHello("Lw")
p1.makeFriends(p2)
}
}
异常处理
object ExceptionDemo {
def main(args: Array[String]): Unit = {
/**
* Java 中异常处理
* try{
* ....
* }catch(Exception){
* ....
* }finally{
* ....
* }
*/
try {
val result = 1/"xx".toInt
}catch {
case e:Exception =>processException(e)
}finally {
println("finally..........")
}
}
//根据不同异常的类型 进行不同的处理
def processException(e:Exception): Unit ={
e match {
case e:ArithmeticException=>{
println("ArithmeticException")
e.printStackTrace()
}
case e:NumberFormatException=>{
println("数字格式化错误")
e.printStackTrace()
}
case e:Exception => e.printStackTrace()
}
}
}