In this tutorial you will learn about classes and objects via simple step by step examples.
Example 1: DataClass
Let us look at a simple DataClass example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
DataClass.kt
- In your editor or IDE, create a file known as
DataClass.kt
. - Then add the following code:
(a). DataClass.kt
package Objects.DataClass
/* This sample demonstrates various features that you get from using a data class */
public data class Superhero(val firstName : String, val lastName : String)
fun main(args : Array<String>) {
var superman = Superhero("clark", "kent")
//Automatic toString generation
println("Superman is ${superman.toString()}")
//Automatic hashCode
println("Superman hashcode is ${superman.hashCode()}")
var supermanAlias = Superhero("clark", "kent")
//Auto generated equals
var areTheyEqual = superman.equals(supermanAlias)
println("Is superman equals supermanAlias? $areTheyEqual")
//component methods are generated
val isFirstName = superman.firstName.equals(superman.component1())
println("is .firstName equal to .component1? $isFirstName ")
var isLastName = superman.lastName.equals(superman.component2())
println("is .lastName equals to .component2? $isLastName")
//multi declarations
val hero = { x : Superhero -> x }
val(firstName, lastName ) = hero(superman)
println("Our superhero name is $firstName $lastName")
//another sample of multi declarations
fun supercharge(x : Superhero) : Superhero {
var m = Superhero(x.firstName.toUpperCase(), x.lastName.toUpperCase())
return m
}
val(firstName2, lastName2) = supercharge(superman)
println("Our supercharged superhero name is $firstName2 $lastName2")
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 2: Constructors
Let us look at a simple Constructors example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Constructors.kt
- In your editor or IDE, create a file known as
Constructors.kt
. - Then add the following code:
(a). Constructors.kt
package Objects.Constructors
class Primary(initialName : String, age : Int = 30) {
var firstName = initialName
val age = age
init {
//this is an anonymous constructor
//there is no other type of constructor
firstName += ".jr"
}
public fun sayName() {
println("My name is $firstName and I am $age years old.")
}
}
fun main(args : Array<String>) {
var p = Primary("John Adams", 56)
p.sayName()
var n = Primary("Bon Jovi")
n.sayName()
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 3: Object Properties
Let us look at a simple Object Properties example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Properties.kt
- In your editor or IDE, create a file known as
Properties.kt
. - Then add the following code:
(a). Properties.kt
package Objects.Properties
fun main(args : Array<String>) {
//you cannot change johnClark name. It's immutable
var johnC = Person("John", "Clark")
println("The name is ${johnC.firstName} ${johnC.lastName}")
var markC = Soldier("Mark", "Chavez")
println("The name is ${markC.firstName} ${markC.lastName}")
var vanD = UniversalSoldier("Van", "Damme")
println("The name is ${vanD.firstName} ${vanD.lastName}")
var slyvesterS = UltimateSoldier("Slyvester", "Stallone")
println("The name is ${slyvesterS.firstName} ${slyvesterS.lastName}")
}
//This will make two immutable properties
class Person(val firstName : String, val lastName : String)
//This is another way to declare the immutable properties.
class Soldier(firstName : String, lastName : String) {
public val firstName : String = firstName
public val lastName : String = lastName
}
//Property with backing field
//The compiler only generates a backing field if it is used by the accessors.
class UniversalSoldier(firstName : String, lastName : String) {
public var firstName : String = firstName
get() {
return "Universal " + field
}
set(value) {
field = value
}
public var lastName : String = lastName
}
//property with old java style
class UltimateSoldier(firstName : String, lastName : String) {
private var _firstName = ""
public var firstName : String
get() {
return _firstName
}
set(value) {
_firstName = value
}
private var _lastName = ""
public var lastName : String
get() {
return _lastName
}
set(value) {
_lastName = value
}
init {
//constructor - we cannot initialize directly to the properties because this way there is no backing field
this.firstName = firstName
this.lastName = lastName
}
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 4: ObjectClass
Let us look at a simple ObjectClass example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
ObjectClass.kt
- In your editor or IDE, create a file known as
ObjectClass.kt
. - Then add the following code:
(a). ObjectClass.kt
package Objects.ObjectClass
fun main(args : Array<String>) {
val espana = Matador("Emilio")
Matador.show(espana)
//you can also assign class object to a variable and use it later
val m = Matador
println("Typeof " + m)
m.show(espana)
//how do you pass it to a parameter
}
class Matador(name : String) {
private val name : String = name
private fun myPrivateShow() {
println("This is ${name} private show")
}
companion object {
fun show(mt : Matador) {
//function inside a class object can access private properties and function of the class
println ("Expose the private secret of ${mt.name}")
mt.myPrivateShow()
}
}
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 5: ExtensionProperties
Let us look at a simple ExtensionProperties example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
ExtensionProperties.kt
- In your editor or IDE, create a file known as
ExtensionProperties.kt
. - Then add the following code:
(a). ExtensionProperties.kt
package Objects.ExtensionProperties
val Amazing.isEmpty : Boolean
get() = this.name.length == 0
class Amazing(name : String) {
var name : String = name
}
fun main(args : Array<String>) {
val italian = Amazing("Roberto")
println("${italian.name} is empty : ${italian.isEmpty}")
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 6: InvokableObjects
Let us look at a simple InvokableObjects example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Invokable.kt
- In your editor or IDE, create a file known as
Invokable.kt
. - Then add the following code:
(a). Invokable.kt
package Objects.InvokableObjects
/* You can use any type that has an operator function named invoke() in a callee position:*/
interface Superhero {
public operator fun invoke()
}
class Batman : Superhero {
override operator fun invoke() {
println ("Batman punches")
}
}
class Superman {
}
// this also works even if it's just an extension function
operator fun Superman.invoke() {
println ("Superman flies")
}
fun invoke(x : Batman) {
x()
}
fun invoke2(x : Superhero) {
x()
}
fun invoke3(x : Superman) {
x()
}
fun main(args : Array<String>) {
var darkNight = Batman()
var clark = Superman()
invoke(darkNight)//direct type
invoke2(darkNight)//via trait
invoke3(clark)//via extension function
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 6: Inheritance
Let us look at a simple Inheritance example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Inheritance.kt
- In your editor or IDE, create a file known as
Inheritance.kt
. - Then add the following code:
(a). Inheritance.kt
package Objects.Inheritance
fun main(args : Array<String>) {
//simple final class
var final = FinalConstruct("Andrew Sullivan")
println("His name is ${final.name}")
//derived class with two traits
var less = LessFlexible("Karl Rove")
println("His name is ${less.name}")
less.dance()
less.sing()
}
class FinalConstruct(var name : String) {
}
open class FlexibleConstruct(var name : String) {
}
interface Singing {
fun sing() {
println("I can sing")
}
}
interface Dancing {
fun dance() {
println("I can dance")
}
}
//You can only have one supertype but multiple interfaces
class LessFlexible(name : String) : FlexibleConstruct(name), Singing, Dancing {
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 7: How to copy a data class
Let us look at a simple example of how to copy a data class. The example is written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
CopyDataClass.kt
- In your editor or IDE, create a file known as
CopyDataClass.kt
. - Then add the following code:
(a). CopyDataClass.kt
package Objects.CopyDataClass
data class Person(val firstName: String, val lastName: String){
public fun print(){
println("$firstName $lastName")
}
}
fun main(args : Array<String>) {
val presidentOne = Person("Bill", "Clinton")
presidentOne.print()
val presidentTwo = presidentOne.copy(firstName = "Hillary")
presidentTwo.print()
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 8: Delegation with Interfaces
Let us look at a simple Delegation via interfaces example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Delegation.kt
- In your editor or IDE, create a file known as
Delegation.kt
. - Then add the following code:
(a). Delegation.kt
package Objects.Delegation
//This is a neat little feature being able to automatically assign an object to handle any interface
fun main(args : Array<String>) {
var me = BruceWayne(Batman(), RichyRich())
me.inWater()
print("Is awesomely rich? " + me.isAwesomelyRich())
}
interface Superpower {
fun inWater()
fun onAir()
fun onSoil()
}
interface Wealth {
fun isAwesomelyRich() : Boolean
}
public class Batman() : Superpower {
companion object {
fun create() = Batman()
}
override fun inWater() {
println("Ack, cannot swim")
}
override fun onAir() {
println("Requires vehicle")
}
override fun onSoil() {
println("Awesome")
}
fun isFun() : Boolean {
return false
}
}
public class RichyRich : Wealth {
override fun isAwesomelyRich() : Boolean {
return true
}
}
public class BruceWayne(a : Batman, b : RichyRich) : Superpower by a, Wealth by b
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 9: Nested class
Let us look at a simple Nested class example written in Kotlin. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Nested.kt
- In your editor or IDE, create a file known as
Nested.kt
. - Then add the following code:
(a). Nested.kt
package Objects.Nested
fun main(args : Array<String>) {
var btm = Batman()
var rbn = Batman.Robin()
btm.say()
rbn.say()
}
public class Batman() {
fun say() {
println("This is Batman")
}
public class Robin {
fun say() {
println("This is Robin")
}
}
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 10: Object Expressions
Let us look at a simple Object Expressions example written in Kotlin. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
ObjectExpressions.kt
- In your editor or IDE, create a file known as
ObjectExpressions.kt
. - Then add the following code:
(a). ObjectExpressions.kt
package Objects.Expressions
fun main(args : Array<String>) {
var alone = object {
val name : String = "Broken Glass House"
val address : String = "55 N. State Street, Chicago"
}
println ("This is the address of the event : '${alone.name}' with address '${alone.address}'")
var killer = object : Player("John Adams") {
override fun fight() {
println ("$name can shoot and run")
}
}
killer.fight()
}
fun anythingGoes() : Any {
return object {
val message : String = "You can use this anytime"
}
}
open class Player(name : String) {
public val name : String = name
public open fun fight() {
println("$name can fight.")
}
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Kotlin Visibility Examples
In this tutorial you will learn about Visibility via simple step by step examples.
Let us look at a simple Visibility example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Cookie.kt
MultipleRef.kt
ObserveAnimals.kt
RecordAnimals.kt
Example 1: Private Member Example
- In your editor or IDE, create a file known as
Cookie.kt
. - Then add the following code:
class Cookie(
private var isReady: Boolean // [1]
) {
private fun crumble() = // [2]
println("crumble")
public fun bite() = // [3]
println("bite")
fun eat() { // [4]
isReady = true // [5]
crumble()
bite()
}
}
fun main() {
val x = Cookie(false)
x.bite()
// Can't access private members:
// x.isReady
// x.crumble()
x.eat()
}
/* Output:
bite
crumble
bite
*/
Example 2: MultipleRef.kt
- Next create another file known as
MultipleRef.kt
. - And add the following code:
// Visibility/MultipleRef.kt
class Counter(var start: Int) {
fun increment() {
start += 1
}
override fun toString() = start.toString()
}
class CounterHolder(counter: Counter) {
private val ctr = counter
override fun toString() =
"CounterHolder: " + ctr
}
fun main() {
val c = Counter(11) // [1]
val ch = CounterHolder(c) // [2]
println(ch)
c.increment() // [3]
println(ch)
val ch2 = CounterHolder(Counter(9)) // [4]
println(ch2)
}
/* Output:
CounterHolder: 11
CounterHolder: 12
CounterHolder: 9
*/
Example 3: Animals Example
- Next create another file known as
RecordAnimals.kt
. - And add the following code:
(d). RecordAnimals.kt
// Visibility/RecordAnimals.kt
private var index = 0 // [1]
private class Animal(val name: String) // [2]
private fun recordAnimal( // [3]
animal: Animal
) {
println("Animal #$index: ${animal.name}")
index++
}
fun recordAnimals() {
recordAnimal(Animal("Tiger"))
recordAnimal(Animal("Antelope"))
}
fun recordAnimalsCount() {
println("$index animals are here!")
}
ObserveAnimals.kt
- Next create another file known as
ObserveAnimals.kt
. - And add the following code:
// Visibility/ObserveAnimals.kt
fun main() {
// Can't access private members
// declared in another file.
// Class is private:
// val rabbit = Animal("Rabbit")
// Function is private:
// recordAnimal(rabbit)
// Property is private:
// index++
recordAnimals()
recordAnimalsCount()
}
/* Output:
Animal #0: Tiger
Animal #1: Antelope
2 animals are here!
*/
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code License |