Location>code7788 >text

Kotlin Object-Oriented Programming (OOP) Basics: Classes, Objects, and Inheritance Explained

Popularity:651 ℃/2024-08-09 14:40:51

What is Object-Oriented Programming (OOP)?

OOP Represents object-oriented programming.

Procedural programming involves writing procedures or methods that perform data manipulation, while object-oriented programming involves creating objects that contain data and methods.

Object-oriented programming has several advantages over procedural programming:

  • OOP Faster and easier to implement
  • OOP Provides a clear structure for the program
  • OOP Helps to keepKotlin codedDRY Principle ("don't repeat yourself") to make code easier to maintain, modify, and debug
  • OOP Enables the creation of complete reusable applications with less code and shorter development time

Tip: "Don't repeat yourself" (DRY - Don't repeat yourself) The principle aims to reduce code duplication. Instead of writing the same code over and over again, you should extract code that is common to your application and put it in one place for reuse.

Kotlin - What are classes and objects?

Classes and objects are the two main aspects of object-oriented programming.

Take a look at the following schematic to understand the difference between a class and an object:

resemble

  • fruit

boyfriend

  • pomegranate
  • bananas
  • pineapple

Another example:

resemble

  • motor vehicles

boyfriend

  • Volvo (Swedish car company)
  • Audi
  • Toyota or Toyoda (name)

Therefore.resemble beboyfriend templates, and theboyfriend beresemble Examples of.

When individual objects are created, they inherit all variables and methods from the class.

Kotlin Classes and Objects

existKotlin In it, everything is related to classes and objects and their properties and functions. For example, in real life, a car is an object. Cars have properties, such as brand, weight, and color; and functions, such as drive and brake.

resemble It's like a constructor for an object, or a "blueprint" for creating an object.

Creating a Class

To create a class, use theclass keyword and specify the name of the class:

typical example

Creates aCar Class:

class Car {
  var brand = ""
  var model = ""
  var year = 0
}

Attributes are basically variables that belong to a class.

Important: For better code organization, it is often recommended that class names begin with a capital letter.

Create an object

Now we can use a file namedCar class to create objects.

In the following example, we have created a file namedc1 (used form a nominal expression)Car object, then use the dot syntax (.) Accessc1 properties, just as we access the properties of arrays and strings:

typical example

// Create the c1 object of the Car class
val c1 = Car()

// Access and assign values to the properties
 = "Ford"
 = "Mustang"
 = 1969

println() // output Ford
println() // outputs Mustang
println() // outputs 1969

multiple object

You can create multiple objects of a class:

typical example

val c1 = Car()
 = "Ford"
 = "Mustang"
 = 1969

val c2 = Car()
 = "BMW"
 = "X5"
 = 1999

println()  // Ford
println()  // BMW

Kotlin Constructors

We have created an object of the class and specified the properties inside the class as shown below:

typical example

class Car {
  var brand = ""
  var model = ""
  var year = 0
}

fun main() {
  val c1 = Car()
   = "Ford"
   = "Mustang"
   = 1969
}

existKotlin This can be done more quickly by using the constructor.

Constructor A constructor is like a special function that is created by using two parentheses after the class name.() to define. You can specify attributes in parentheses (just like passing arguments to a normal function).

The constructor initializes the attributes when you create an object of the class. Just remember to specify the type of the attribute/variable:

typical example

class Car(var brand: String, var model: String, var year: Int)

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)
}

It's now even easier to specify multiple objects of a class:

typical example

class Car(var brand: String, var model: String, var year: Int)

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)
  val c2 = Car("BMW", "X5", 1999)
  val c3 = Car("Tesla", "Model S", 2020)
}

Kotlin Class Functions

You can also use functions inside classes to perform certain operations:

typical example

existCar class to create adrive() function and call it:

class Car(var brand: String, var model: String, var year: Int) {
  // Class function
  fun drive() {
    println("Wrooom!")
  }
}

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)

  // Call the function
  ()
}

Tip: When a function is declared inside a class, it is called a class function or a member function.

Note: When an object of a class is created, it has access to all class functions.

class function parameter

As with normal functions, you can pass parameters to class functions:

typical example

Create two functions:drive() cap (a poem)speed()and tospeed() function to pass parameters:

class Car(var brand: String, var model: String, var year: Int) {
  // Class function
  fun drive() {
    println("Wrooom!")
  }

  // Class function with parameters
  fun speed(maxSpeed: Int) {
    println("Maximum speed is: " + maxSpeed)
  }
}

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)

  // Call the function
  ()
  (200)
}

Kotlin Inheritance

existKotlin In this case, it is possible to inherit class attributes and functions from one class to another. We categorize "inheritance concepts" into two groups:

  • child - A class that inherits from another class.
  • parent - a class that is inherited.

In the following example, theMyChildClass(subclass) inherits theMyParentClass attributes of the class (superclass):

typical example

// Superclasses
open class MyParentClass {
  val x = 5
}

// Subclasses
class MyChildClass: MyParentClass() {
  fun myFunction() {
    println(x) // x is now inherited from the superclass.
  }
}

// Create an object of MyChildClass and call myFunction.
fun main() {
  val myObj = MyChildClass()
  ()
}

illustrative example

  • utilizationopen The keyword modifies the superclass/parent class so that the class can inherit attributes and functions from other classes.
  • To inherit a class, specify the name of the subclass followed by a colon:, and then the name of the superclass.

Why and when is "inheritance" used?

  • It is useful for code reuse: properties and functions of existing classes can be reused when creating new classes.

ultimate

To make it easier for peeps on other devices and platforms to view past articles:

WeChat Search:Let us CodingFollow to get the latest articles tweeted

If you find it helpful, please like, favorite and follow it!