4.1. Classes and Objects
Table of Contents
Overview
In Kotlin, object oriented programming is centered around classes and objects. A class is a blueprint that describes what something is and what it can do. An object is a real instance created from that blueprint. In Android apps you constantly work with classes, such as Activity, View, and Intent, and you create objects from these classes to make your app do real work.
In this chapter you will learn how to declare your own classes, create objects from them, define properties and functions inside them, and understand how Kotlin handles these concepts in a concise way.
Defining a Simple Class
A basic class in Kotlin is declared with the class keyword followed by a name. By default, such a class has no properties and no behavior until you add them.
class User {
}
This example defines a class named User. It is just an empty blueprint. To make it useful, you add properties and functions inside its body.
Kotlin lets you omit the curly braces when the class has no body.
class Empty
You can put classes in their own .kt files, often with the same name as the class. For example, a class named User is typically defined in a file named User.kt. This keeps your project organized and easier to navigate, especially as an Android app grows.
Properties Inside a Class
Properties are variables that belong to a class. Each object created from that class has its own copy of these properties, which together represent the state of that object.
Inside a class, you declare properties using val for read only values or var for mutable values.
class User {
var name: String = ""
var age: Int = 0
val isAdult: Boolean = false
}
Here each User object has a name, an age, and an isAdult flag. When you create multiple User objects, each one can have different values.
Kotlin lets you write property declarations in a compact way and initializes them directly inside the class. You will learn more about initialization when working with constructors, but at this stage it is useful to see that properties are associated with each object, not the class itself.
Creating Objects
Once you have a class, you can create objects from it. Creating an object is also called instantiating a class.
By default, if a class has a simple primary constructor with no parameters, you can create an object using the class name followed by parentheses.
val user = User()
Here user is an object of type User. The type can be written explicitly.
val user: User = User()
Each new call to User() creates a different object with its own properties. So if you create two users, they do not share their values.
val user1 = User()
val user2 = User()
user1.name = "Alice"
user2.name = "Bob"
In this example user1.name is "Alice" and user2.name is "Bob", because each object has its own state.
Accessing Properties and Functions
You use the dot operator to work with the members of an object. A member can be a property or a function defined in the class.
For properties, you read and write values like this:
user.name = "Charlie"
println(user.name)
This is similar to how you will work with Android classes. For example, calling textView.text = "Hello" or accessing properties in a Button uses the same idea.
You can think of the dot operator as a way to say “use this thing that belongs to that object.”
Methods: Functions Inside Classes
Functions defined inside a class are often called methods. They describe what objects of that class can do. You define them similarly to normal functions, but they are placed inside the class body.
class User {
var name: String = ""
var age: Int = 0
fun printInfo() {
println("Name: $name, age: $age")
}
fun birthday() {
age = age + 1
}
}
Here printInfo and birthday are methods of the User class. You call them on an object with the dot operator.
val user = User()
user.name = "Dana"
user.age = 20
user.printInfo() // prints: Name: Dana, age: 20
user.birthday()
user.printInfo() // prints: Name: Dana, age: 21
Inside these methods, you can directly access the properties name and age. Kotlin automatically refers to the current object.
The `this` Reference
Sometimes you need to refer explicitly to the current object inside a class. Kotlin provides the keyword this for that purpose. It represents the object on which the method or property is currently operating.
In many cases you do not need to write this because Kotlin can infer it. However, it is useful when a parameter name is the same as a property name.
class User {
var name: String = ""
fun setName(name: String) {
this.name = name
}
}
Here the class has a property name and the method setName has a parameter also called name. In the body, this.name refers to the property, and name by itself refers to the parameter. This is a common pattern when you want to update properties from function arguments.
this can also help clarify code, especially in more complex classes. For example, you might write this.printInfo() to show you are calling a method on the current object.
Initializing Objects and Default Values
In the earlier examples, properties are given default values directly when declared. When you instantiate the class, each object starts with those default values. For instance, name might start as an empty string and age as zero.
Kotlin also supports more advanced ways to pass initial values when you create objects, which involves constructors. Since constructors are covered as a separate topic, here you only need to observe that simple classes can rely on default property values, and you can change them after object creation using the dot operator.
Important: Every object has its own copy of instance properties. Changing a property on one object does not change the same property on another object created from the same class.
This separation of state between objects is a core part of object oriented programming and is heavily used in Android. For example, two different Button objects can each have their own text and their own click behavior.
Instance vs Class Level Members (Preview)
So far, every property and function you have seen belongs to an individual instance of the class. These are called instance members, because they are tied to a specific object that you created.
Sometimes you need behavior or data that belongs to the class itself, not to any particular object. Kotlin supports this through companion object or top level declarations. These ideas are introduced in more detail elsewhere. At this point, it is enough to understand that there is a difference between things that exist per object and things that exist once for the whole class.
An Android example that uses this idea is a constant defined once and used by all activities, such as an extra key for an Intent.
Using Classes and Objects in Android
In Android development, you rarely work with raw Kotlin classes only for learning. Instead, you create classes that extend Android framework classes and define objects that interact with the system and the user interface.
When you define your own model classes, such as User, Product, or Message, you use the same patterns shown in this chapter. You declare properties that represent data, add methods that work with that data, and then create objects to pass around in your app, for example to display a list of users in a RecyclerView.
Understanding how to declare classes, create objects, and use properties and methods is therefore a foundation that will keep appearing in almost every Android feature you implement.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Introduction to Android Development
- ☰ 1.1. What is Android
- ☰ 1.2. Android Ecosystem and Versions
- ☰ 1.3. Native vs Cross-Platform Development
- ☰ 1.4. Course Structure and Goals
-
- ☰ 2. Setting Up the Development Environment
- ☰ 2.1. Installing Android Studio
- ☰ 2.2. Android SDK and Tools
- ☰ 2.3. Emulator Setup
- ☰ 2.4. Running Apps on a Physical Device
-
- ☰ 3. Kotlin Basics for Android
- ☰ 3.1. Variables and Data Types
- ☰ 3.2. Control Flow (if, when, loops)
- ☰ 3.3. Functions
- ☰ 3.4. Null Safety
- ☰ 3.5. Packages and Imports
-
- ☰ 4. Object-Oriented Programming in Kotlin
- ☰ 4.1. Classes and Objects
- ☰ 4.2. Constructors
- ☰ 4.3. Inheritance and Polymorphism
- ☰ 4.4. Interfaces
- ☰ 4.5. Data Classes and Enums
-
- ☰ 5. Android Project Structure
- ☰ 5.1. Android Studio Project Overview
- ☰ 5.2. Gradle Build System
- ☰ 5.3. AndroidManifest.xml
- ☰ 5.4. Resource Directories
-
- ☰ 6. Your First Android App
- ☰ 6.1. Creating a New Project
- ☰ 6.2. Understanding MainActivity
- ☰ 6.3. Running and Debugging the App
-
- ☰ 7. Android App Lifecycle
- ☰ 7.1. Activity Lifecycle
- ☰ 7.2. Lifecycle Callbacks
- ☰ 7.3. Configuration Changes
-
- ☰ 8. Layouts and Views
- ☰ 8.1. XML Layout Basics
- ☰ 8.2. LinearLayout
- ☰ 8.3. ConstraintLayout
- ☰ 8.4. View Attributes
- ☰ 8.5. Responsive Layouts
-
- ☰ 9. User Interaction
- ☰ 9.1. Buttons and Click Listeners
- ☰ 9.2. TextView and EditText
- ☰ 9.3. Handling User Input
- ☰ 9.4. Toasts and Snackbars
-
- ☰ 10. Styling and Themes
- ☰ 10.1. Colors and Dimensions
- ☰ 10.2. Styles
- ☰ 10.3. Themes
- ☰ 10.4. Dark Mode Support
-
- ☰ 11. Navigation Between Screens
- ☰ 11.1. Intents
- ☰ 11.2. Passing Data Between Activities
- ☰ 11.3. Activity Back Stack
-
- ☰ 12. Fragments
- ☰ 12.1. Fragment Basics
- ☰ 12.2. Fragment Lifecycle
- ☰ 12.3. Fragment Transactions
- ☰ 12.4. Fragment Communication
-
- ☰ 13. RecyclerView and Lists
- ☰ 13.1. RecyclerView Basics
- ☰ 13.2. Adapters and ViewHolders
- ☰ 13.3. Click Handling in Lists
-
- ☰ 14. Data Storage Basics
- ☰ 14.1. SharedPreferences
- ☰ 14.2. Internal Storage
- ☰ 14.3. File Handling
-
- ☰ 15. Databases with Room
- ☰ 15.1. SQLite Overview
- ☰ 15.2. Room Entities
- ☰ 15.3. Data Access Objects
- ☰ 15.4. Database Migrations
-
- ☰ 16. Working with Images and Media
- ☰ 16.1. ImageView and Drawable Resources
- ☰ 16.2. Loading Images from the Internet
- ☰ 16.3. Audio and Video Playback
-
- ☰ 17. Permissions and Security
- ☰ 17.1. App Permissions
- ☰ 17.2. Runtime Permissions
- ☰ 17.3. Security Best Practices
-
- ☰ 18. Networking Fundamentals
- ☰ 18.1. HTTP Basics
- ☰ 18.2. REST APIs
- ☰ 18.3. JSON Parsing
-
- ☰ 19. Networking with Retrofit
- ☰ 19.1. Retrofit Setup
- ☰ 19.2. API Interfaces
- ☰ 19.3. Error Handling
-
- ☰ 20. Background Tasks
- ☰ 20.1. Threads and Handlers
- ☰ 20.2. Kotlin Coroutines
- ☰ 20.3. Lifecycle-Aware Tasks
-
- ☰ 21. Services and WorkManager
- ☰ 21.1. Services Overview
- ☰ 21.2. Foreground vs Background Services
- ☰ 21.3. WorkManager
-
- ☰ 22. Architecture Components
- ☰ 22.1. ViewModel
- ☰ 22.2. LiveData
- ☰ 22.3. MVVM Architecture
-
- ☰ 23. Dependency Injection
- ☰ 23.1. Dependency Injection Concepts
- ☰ 23.2. Hilt Basics
-
- ☰ 24. Material Design
- ☰ 24.1. Material Design Principles
- ☰ 24.2. Material Components
- ☰ 24.3. Adaptive UI Design
-
- ☰ 25. Animations and Motion
- ☰ 25.1. View Animations
- ☰ 25.2. Property Animations
- ☰ 25.3. Transitions
-
- ☰ 26. Notifications
- ☰ 26.1. Notification Basics
- ☰ 26.2. Notification Channels
- ☰ 26.3. Action Buttons
-
- ☰ 27. Location and Sensors
- ☰ 27.1. Location Services
- ☰ 27.2. Using GPS
- ☰ 27.3. Device Sensors
-
- ☰ 28. Maps and Geolocation
- ☰ 28.1. Google Maps Integration
- ☰ 28.2. Markers and Map Events
-
- ☰ 29. Testing Android Apps
- ☰ 29.1. Unit Testing
- ☰ 29.2. UI Testing with Espresso
-
- ☰ 30. Performance Optimization
- ☰ 30.1. Memory Management
- ☰ 30.2. Profiling Tools
- ☰ 30.3. Performance Best Practices
-
- ☰ 31. App Debugging
- ☰ 31.1. Logcat
- ☰ 31.2. Breakpoints
- ☰ 31.3. Debugging Common Issues
-
- ☰ 32. App Packaging and Signing
- ☰ 32.1. APK vs AAB
- ☰ 32.2. Signing Configurations
- ☰ 32.3. Release Builds
-
- ☰ 33. Publishing on Google Play
- ☰ 33.1. Google Play Console
- ☰ 33.2. Store Listing
- ☰ 33.3. Release Tracks
-
- ☰ 34. Monetization Strategies
- ☰ 34.1. Ads
- ☰ 34.2. In-App Purchases
- ☰ 34.3. Subscriptions
-
- ☰ 35. Advanced Topics
- ☰ 35.1. Custom Views
- ☰ 35.2. Introduction to Jetpack Compose
-
- ☰ 36. Capstone Project
- ☰ 36.1. Project Planning
- ☰ 36.2. Implementation
-
Comments
Please login to add a comment.
Don't have an account? Register now!