From the course: Build Spring Boot Apps with the Kotlin Programming Language
Instantiating a class and accessing class-level attributes
From the course: Build Spring Boot Apps with the Kotlin Programming Language
Instantiating a class and accessing class-level attributes
- [Instructor] So, to work with this class, let's create a Main Method. I think I'll get rid of this second class, for the moment. I'm sure we'll be creating more classes in just a few minutes, but let's have a Main Method and we can create that as a top level function. It doesn't have to sit within a class, as we know, and it can be in this file, no reason why not. So, let's create our Main Method by typing in Main and pressing Enter. Now, I think we've already said that you can instantiate a class in a similar way to you do in Java. The idea is we're going to create a variable and set it equal to a new instance of our class. So, let's start with the variable, which I think we'll call customer, in lower case. And while we don't use the new keyword, we simply say, it's a Customer with a capital C, and we need our open and close brackets. So, let's print out the Customer's name, and in Kotlin, the fields in a class are public by default. So, I can just reference .Name. Let's just do that to check it works. Good, so there's the name printed out to the console. So, in Kotlin, we don't call a Get or a Set Method to address a variable. I guess because they're pubic by default, but if for example, I made one of these into a var, let's change the age to a var. I'd then be able to change that value by doing customer.age equals, let's make mine 22, maybe I've had a year's birthday. And we'll print that out. I think we'll change this now to be a String that says, $(cutomer.name) is $(customer.age) years old. And again, we'll just run that and check that works. So, in Kotlin, we reference the fields directly. We don't call Get and Set, and we can create those. I will talk a bit about Get and Set in a little while, but for the moment, all the fields are public and we just reference them directly. And that can actually be a safe thing to do, because ideally we're going to make our fields vals, which means there should be no issue calling the .Get or the equivalence of a .Get on that field.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
-
(Locked)
Project structure and packages2m 5s
-
(Locked)
The class declaration and class-level attributes3m 31s
-
Instantiating a class and accessing class-level attributes2m 14s
-
(Locked)
Creating a simple constructor5m 7s
-
(Locked)
Secondary constructors5m 20s
-
(Locked)
Alternative class design5m 3s
-
(Locked)
Overriding getters and setters7m 21s
-
(Locked)
Functions within a class2m 57s
-
(Locked)
Static functions3m 28s
-
(Locked)
Data classes7m 32s
-
(Locked)
-
-
-
-
-
-
-
-
-
-
-
-
-
-