Scala abstract class

Article Directory

1 Overview

If there are abstract fields or abstract methods in the class, then the class should be an abstract class

  • Abstract field: A variable without an initial value is an abstract field
  • Abstract method: A method without a method body is an abstract method

2. Format

//定义抽象类
abstract class 抽象类名 {
    
    
	//定义抽象字段
	val/var 抽象字段名:类型
	//定义抽象方法
	def 方法名(参数:参数类型,参数:参数类型...):返回值类型
}

3. Case

demand:
Insert picture description here

  • Design 4 classes to represent the inheritance relationship in the above figure
  • Each shape has its own method of calculating area, but different shapes have different methods of calculating area

Code:

object demo {
    
    
  //定义抽象类
  abstract class Shape{
    
    
    def area():Double;
  }
  //创建Square(正方形)类
  class square(length:Int) extends Shape{
    
    
    override def area(): Double = return length*length;
  }
  //创建rectangle(长方形)类
  class rectangle(length:Int,wide:Int) extends Shape{
    
    
    override def area(): Double = return length*wide;
  }
  //创建circle(圆形)类
  class circle(R:Int) extends Shape{
    
    
    override def area(): Double = return Math.PI*R*R;
  }

  def main(args: Array[String]): Unit = {
    
    
    var area1=new square(2);
    println(area1.area());
    var area2=new rectangle(2,3);
    println(area2.area());
    var area3=new circle(2);
    println(area3.area());
  }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/zh2475855601/article/details/114686092