演员阵容永远不会成功

时间:2017-07-25 17:54:13

标签: oop casting kotlin

我是Kotlin的新人,我目前正在研究OOP的概念

我正在尝试使用此代码进行演员,但我遇到了错误:

open class Operations1(){
open  fun sum(n1:Int , n2:Int):Int{
    return n1+ n2
}
fun sub(n1:Int , n2:Int):Int{
    return n1- n2
}
}
class multiOperations1():Operations(){
override  fun sum(n1:Int , n2:Int):Int{
    return n1+ n2 +5
}
fun mul(n1:Int , n2:Int):Int{
    return n1* n2
}
fun div(n1:Int , n2:Int):Int{
    return n1/ n2
}
}
fun main(args:Array<String>){

var oper = Operations()
var inlit  = multiOperations1() as Operations1
println("Enter first number")
var n1:Int = readLine()!!.toInt()
println("Enter Second Number")
var n2:Int = readLine()!!.toInt()

var sum = inlit.sum(n1 , n2)
var sub = inlit.sub(n1 , n2)
println("Sum: " + sum)
println("Sub: " + sub)
}

代码的屏幕截图

This is the screen shot of the code

错误:

This is the error which my program through

3 个答案:

答案 0 :(得分:2)

要实现这一目标,您可以简单地使用Gson并避免样板代码:

var operation= Operations(....)

val json = Gson().toJson(operation)

val multiOperations:MultiOperations =Gson().fromJson(json, MultiOperations::class.java)

答案 1 :(得分:1)

您似乎同时拥有OperationsOperations1类。您的multiOperations1类继承自Operations而不是Operations1,因此您无法将其强制转换为Operations1(除非Operations是{的子类{1}})。

我假设你想从Operations1继承,就像这样:

Operations1

关于约定的注释:Kotlin中的类名通常遵循Java约定,并使用上部驼峰大小写,因此您应该将类​​命名为class multiOperations1(): Operations1() { ... }

答案 2 :(得分:0)

你可以使用 -

 var inlit  = multiOperations1() as Operations

您可以将派生类强制转换为父类。在您的情况下,multiOperations1类具有父类Operations

只是一个建议从大写字母开始你的类名multiOperations1

相关问题