Home > database >  Accessing members in a superclass from a base class
Accessing members in a superclass from a base class

Time:11-30

Here's an example of inheritance in Kotlin:

abstract class Animal(val size: Int)
class Dog(val cuteness: Int): Animal(345)

var dog: Dog = Dog(10)
var animal: Animal = dog

var x = 0
...

If you put a breakpoint on the last line, the variable animal will be set to the instance of dog. However, you can only access the size member in Animal. You can't access the cuteness member in Dog. But Android Studio's debugger still lets you see the value of the cuteness member in the animal variable.

Is there a way in code to access those hidden members? I don't think there is. I think that Android Studio knows what they are and shows them to you for debugging purposes, but because they are not accessible through Kotlin, it will prevent you from actually accessing them in code. Maybe I'm wrong?

CodePudding user response:

You just need to use casting :

Cast the animal(object) to Dog Type and you can access cuteness the field you can also change its value if you desire

  val dog: Dog = Dog(10)
  val animal: Animal = dog

  println(animal.size)
  println((animal as Dog).cuteness)

I admit this is not the best solution but it works fine

CodePudding user response:

You want access the cuteness of the animal. You must using for that.

(animal as Dog).cuteness

CodePudding user response:

I'm not sure, but would it throw all the things that inheritance offers if the parent type has access to its child only specific properties?

The only way I can think of is the Animal have an open property cuteness that can be inherited by its children

abstract class Animal(val size: Int, open val cuteness: Int)

class Dog(override val cuteness: Int): Animal(345, cuteness)

this way, Dog instance or any instance declared as Animal type can call the cuteness like the way you want it to

animal.cuteness

or simply like the other answer, just casting it back to Dog type

CodePudding user response:

I know the question is answered but I want to say some additional informations.

Well when you declare animal variable you set its type to Animal, to animal can't be anything else, and if you assign to it a type that inherits from Animal like Dog, the Dog is going to be casted to an Animal and that's what's happening for your case so you have access to animal members only.

But you are able to cast that Animal back to it's original type which is Dog using as:

(animal as Dog).cuteness

But be careful if the Animal is not a Dog your program will crash, so you can use safe cast with as? which is going to return a nullable Dog?, if something goes wrong it's going to return null instead of throwing an exception:

val safeDog: Dog? = (animal as? Dog)
safeDog?.cuteness
  • Related