Class has
● optional Constructors
○ Primary Constructor (var & val Parameters are converted into Properties)
○ Secondary Constructors (If both exist Secondary must call Primary)
● can extend single Class (Extended Class & overridden Method must be open. Use super to reference Parent.)
● can Implement multiple Interfaces.
Use this to reference members.
Basic Class Syntax
class Soldier constructor(name: String, age: Int) : Person, InterfaceA, InterfaceB { ... }
Primary & Secondary Constructors
//===========================================================================================================
// CLASS: Person
//===========================================================================================================
class Person(public var name: String, age: Int) { //Variable Parameters are converted into Properties.
private var age : Int = 0 //Declare Properties.
init { this.age = age } //Primary Constructor Implementation.
constructor(name: String) : this(name, 50) { println("Constructed $name") } //Call Primary Constructor
fun greet() { println("$name is $age years old") } //Method.
}
//===========================================================================================================
// FUNCTION: main
//===========================================================================================================
fun main() {
var person = Person("John", 20) //Call Primary Constructor
person = Person("John") //Call Secondary Constructor
person.greet() //Call public Method: "John is 50 years old"
print(person.name) //Call public Property: "John"
}
Extend Class
//===========================================================================================================
// PARENT CLASS: Person
//===========================================================================================================
open class Person(var name: String) { //open allows Class to be extended
open fun greet() { println(name) } //open allows Method to be overriden
}
//===========================================================================================================
// CHILD CLASS: Soldier
//===========================================================================================================
class Soldier : Person { //Extend from Person Class
constructor(name: String) : super(name) { super.greet() } //Call Parent's Constructor & Method
override fun greet() { println("Hello $name") } //Override Parent's Method
}
//===========================================================================================================
// FUNCTION: main
//===========================================================================================================
fun main() {
var soldier = Soldier("John") //Create Object from Class Soldier.
soldier.greet() //Reference overriden method.
println(soldier.name) //Reference inherited Property.
}