Inheitance Kotlin question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Inheitance Kotlin question

Here is the question which we have to solve and As the images have the same width and height properties, you decide to create a base class called Component and inherit the Button and Image classes from it. The Button class should have its own name property and tap() function, while the Image class should have a draw() function, outputting its height and width in the format: widthheight. So for an image with width of 100 and height of 150, the output should be 100x150. Complete the given code to define the Image class and inherit the Button and Image classes from the Component class. Note, that width and height are Integers, so in order to concatenate them to a string you need to convert them using the toString() function: width.toString() Here is my code but i dont know where i have done mistakes please one retify my mistake and tell me which position i have to modify the code open class Component(var width: Int, var height: Int) { } open class Button(width: Int, height: Int):Component { var name: String = "Button" fun tap() { println(name + " was tapped") } } class Image(width:Int, height:Int):Button{ fun draw(){ println(width.toString+"x"+height.toString) } } fun main(args: Array<String>) { val b1 = Button(200, 50) b1.tap() val img = Image(300, 500) img.draw() }

2nd Jun 2021, 11:05 AM
Abhishek Biswas
Abhishek Biswas - avatar
2 Answers
+ 4
A couple of mistakes. Class inheritance requires passing the required parameters to the super class. toString is a function not a property. https://code.sololearn.com/cxDndM14q9RH
11th Jun 2021, 12:37 AM
John Wells
John Wells - avatar
0
Here my solution / Aqui dejo mi solución open class Component(var width: Int, var height: Int) { } class Button(width: Int, height: Int,var name: String): Component(width, height) { fun tap() { println(name + " was tapped") } } class Image(width: Int,height: Int): Component(width, height){ fun draw(){ println(width.toString()+"x"+height.toString()) } } fun main(args: Array<String>) { val b1 = Button(200, 50,"Button") b1.tap() val img = Image(300, 500) img.draw() }
7th Feb 2023, 11:41 PM
Alejandro Huerta
Alejandro  Huerta - avatar