什么是抽象类?
抽象类就是类的抽象,
定义:抽象类是一个包含一个或多个抽象方法的类。抽象方法是不带任何实现的方法。抽象类也可以包含具体的方法和属性。
抽象类的作用与用法
1.一个抽象类,不能被new, 一个类不能被直接用来创建对象,那么这个类有什么用? 答:做别人的父类 2.可以定义抽象方法,在子类中去实现
object day4 {
abstract class AICar {
// 抽象方法:没有具体的函数代码。
def autoEn():Unit
// 具体方法
def autoDrive ():Unit={
println("具体方法,自动驾驶.....")
}
}
class SU7 extends AICar{// 在子类中,一定要去实现父类的抽象方法
override def autoEn(): Unit = {
println(s"采用小米独家的无线充电技术,停车就可以充电") // 把父类的抽象给实现
}
}
def main(args: Array[String]): Unit = {
// val car1 = new AICar()
val su= new SU7()
su.autoDrive()
}
}
一个抽象中可以有:
1.具体属性: val name:String = "小米"
2.具体方法: def autoRun():Unit={}
3.抽象属性: val name:String 没有具体值的属性。只有属性名和类型。他必须写在抽象类中
4.抽象方法: def autoRun(): Unit 在子类中,要有具体的实现。
/*
3.
*/
object day42 {
abstract class AICar() {
// 1. 具体属性
var name:String = "car"
val color:String = "black"
// 2. 具体方法
def run():Unit = {
println("AICar run.....")
}
// 3. 抽象属性,没有属性值
var price:Double
// 4. 抽象方法,没有方法体
def autoRun():Unit
}
class XiaoMI extends AICar{
// 重写
// 1. 具体属性
name = "小米" // 对于var的属性,直接覆盖
override val color = "流光紫" // 对于val的属性,要添加override
// 2. 具体方法
override def run(): Unit = {
println("小米 run.....")
}
// 实现
// 3. 实现抽象属性
var price = 28.8
// 4. 实现抽象方法
def autoRun():Unit = { println("小米自动驾驶 ")}
}
def main(args: Array[String]): Unit = {
var c1 = new XiaoMI()
c1.autoRun()
c1.run()
println(c1.name)
println(c1.color)
}
}
内部类:
1.在一个类的里面,再写一个类 2.作用:组织逻辑更加严谨
object day43 {
// 外部类
class Car() {
var wheel: Int = 3
// 私有成员
private var speed: Int = 0
def run(): Unit = {
println(s"速度为${speed}, run.....")
}
// 内部类
class Engin() {
def acc(increment: Int): Unit = { // 在内部类中,直接访问私有成员
speed += increment
}
}
class AutoPark(){}
}
def main(args: Array[String]): Unit = {
val c1 = new Car();
var en = new c1.Engin()
en.acc(10)