Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger
  • Frits Walraven

Problem with this constructor chaining and virtual method invocation

Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
open class Person( open var age: Int,  name: String) {
   init {
       println("My name is $name.")
       println("My age is $age")

class MathTeacher( override var age :Int,  var name : String): Person(age,name) {

   fun teachMaths() {
       println("I teach in primary school $age")

class Footballer(age: Int, name: String): Person(age, name) {
   fun playFootball() {
       println("I play for LA Galaxy.")

fun main(args: Array<String>) {
   val t1 = MathTeacher(25, "Jack")

   val f1 = Footballer(29, "Christiano")

So when I run this code the first thing called is the base class constructor, I get that , then it does assignment, I don’t understand why when I am printing the name and age I don’t get a null and zero value,
Posts: 15545
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you expect null and 0? The values you pass to the subclass constructors get passed to the superclass Person constructor and that's what gets printed.
Ranch Foreman
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code-tags make reading code easier:
look! it's a bird! it's a plane! It's .... a teeny tiny ad
Two software engineers solve most of the world's problems in one K&R sized book
    Bookmark Topic Watch Topic
  • New Topic