Lesson 3 Classes and objects
Lesson 3 Classes and objects
Classes and
objects
Object
● Classes are blueprints for objects
instances
● Classes define methods that operate
on their object instances
Class
Data
● House color (String)
● Number of windows (Int)
● Is for sale (Boolean)
Behavior
● updateColor()
● putOnSale() FOR SALE
● Parameters
○ Not marked with var or val → copy exists only within scope of the
constructor
class B(x: Int)
○ Marked var or val → copy exists in all instances of the class
class C(val y: Int)
This work is licensed under the Apache 2 license.
Apache 2 license
class Box(val length: Int, val width:Int = 20, val height:Int = 40)
val box1 = Box(100, 20, 40)
val box2 = Box(length = 100)
val box3 = Box(length = 100, width = 20, height = 40)
val s = Square(10)
=> 20
If you don't want to be limited by only inheriting a single class, you can define an
interface since you can implement as many of those as you want.
val c = Circle(3.0)
println(c.computeArea())
=> 28.274333882308138
To extend a class:
● Create a new class that uses an existing class as its core
(subclass)
● Add functionality to a class without creating a new one
(extension functions)
Try to subclass A
class B : A
Declare a class
open class C
Subclass from C
class D : C()
● Must use open for properties and methods that can be overridden
(otherwise you get compiler error)
● You can extend only one class, but implement one or more interfaces.
● Separate out core API from helper methods for classes you
own
Define extension functions in an easily discoverable place such as in the same file
as the class, or a well-named function.
3.isOdd()
● Generates getters for each property (and setters for vars too)
println(Calculator.add(2,4))
=> 6
● You can and should group related structures in the same file
package org.example.game
org.example.vehicle.moped org.example.vehicle.car
Moped Car
Moped50cc Sedan
Moped100cc Hatchback