当前位置:网站首页>Kotlin introductory notes (V) classes and objects, inheritance, constructors
Kotlin introductory notes (V) classes and objects, inheritance, constructors
2022-07-05 09:14:00 【Meng Meng Mu Xi】
Preface : This tutorial is best done with JAVA Study on the basis of
One 、 Classes and objects
use class Keyword to declare a class , And java identical .
eg.
(1) Define a Person class :
class Person {
var name = ""
var age = 0
fun eat() {
println(name + " is eating. He is " + age + " years old.")
}
}
(2) Instantiation Person This class :
val p = Person()
kotlin Give up java Of new keyword . The reason for doing this , Because you call the constructor of a class , Your intention can only be to initialize this class .
(3)main Function :
fun main() {
val p = Person()
p.name = "Jack"
p.age = 19
p.eat()
}
Run a screenshot :
Two 、 Inherit
I have to mention that kotlin Several characteristics of :
Kotlin Characteristics of :
Kotlin By default, all non abstract classes cannot be inherited
eg:
Now I define a Student class , Want it to inherit just Person class
class Student {
var sno = ""
var grade = 0
}
Just now Person Class cannot be inherited , You need to add open keyword , As shown in the figure below :
open class Person {
var name = ""
var age = 0
fun eat() {
println(name + " is eating. He is " + age + " years old.")
}
}
Combined with the open The keyword is followed by the compiler ,Person This class is designed specifically for inheritance . such Person Class is allowed to be inherited .
And then let Student Class can inherit Person class , as follows :
class Student : Person() {
var sno = ""
var grade = 0
}
Kotlin Of Inherited keywords are also heavy extends Change into : , This is for those who have learned C# My friends are more familiar . But why is there a pair of parentheses after the inherited class ? Because it involves Java Provisions for inherited characteristics , The constructor of the subclass must call the constructor of the parent class , This rule is in Kotlin We should also abide by . It will be explained later Primary constructor and The secondary constructor 了 .
3、 ... and 、 Constructors
(1) Primary constructor
Each class will have a main constructor without parameters by default ( Same as java Constructor for ). Of course, you can also display the declaration parameters . But notice , The primary constructor has no body !
class Student(val sno : String , val grade : Int) : Person() {
}
Instantiation :
val student = Student("a123",5)
But , The primary constructor has no body , How to implement some logic ?
Kotlin It provides us with a init Structure , All the logic in the main constructor can be written in it :
class Student (val sno : String , val grade : Int) : Person() {
init {
println("sno is " + sno)
println("grade is " + grade)
}
}
(2) The secondary constructor
Kotlin Regulations ,
- Any class has only one primary constructor , But there can be many times constructors .
- The secondary constructor can instantiate a class , But it has a function body .
- When a class already has Primary constructor And then there is The secondary constructor , All secondary constructors must call the primary constructor ( Including indirect calls ).
eg.
Learn from the above ,Person The class of can also be written like this :
open class Person(val name : String , val age : Int) {
fun eat() {
println(name + " is eating. He is " + age + " years old.")
}
}
So we let Student class To inherit Person class
class Student (val sno : String , val grade : Int , name : String , age : Int) : Person(name , age) {
constructor(name : String ,age : Int) : this("",0,name,age) {
}
constructor() : this("" , 0) {
}
}
The secondary constructor is by constructor Keywords to define , Here we define two secondary constructors : The first secondary constructor receives name and age Parameters of ; The second constructor does not accept any parameters , It passes through this Called our first constructor , And will name and age Initial value of Fu . Because of the second one The secondary constructor Indirectly call the first The secondary constructor , So it is still legal .
So now we have three ways to be right Student initialization :
val student1 = Student()
val student2 = Student("Tom",15)
val student3 = Student("a123",5,"Jack",18)
A special case :
There are only secondary constructors in a class , There is no primary constructor . This is a rare case , But in Kotlin Is allowed . When a class does not explicitly define a primary constructor and defines a secondary constructor , It just doesn't have a primary constructor .
class Student : Person {
constructor(name : String , age : Int) : super(name,age){
}
}
First ,Student There is no definition shown after the class Primary constructor , At the same time, because of the definition The secondary constructor , So now Student There is no primary constructor . So since there is no primary constructor , Inherit Person Class, there is no need to add brackets . Because there is no primary constructor , The secondary constructor can only call the constructor of the parent class , Call the parent constructor and Java identical , Use super keyword . No more talk here .
If you like this series , You might as well pay attention ! Thank you for watching !
Reference resources :
《 First line of code Android ( The third edition )》 --- Guo Lin
边栏推荐
- Illustrated network: what is gateway load balancing protocol GLBP?
- Newton iterative method (solving nonlinear equations)
- Confusion matrix
- How many checks does kubedm series-01-preflight have
- Applet (use of NPM package)
- Configuration and startup of kubedm series-02-kubelet
- The combination of deep learning model and wet experiment is expected to be used for metabolic flux analysis
- Transfer learning and domain adaptation
- C#绘制带控制点的Bezier曲线,用于点阵图像及矢量图形
- AUTOSAR从入门到精通100讲(103)-dbc文件的格式以及创建详解
猜你喜欢
Solutions of ordinary differential equations (2) examples
nodejs_ 01_ fs. readFile
Global configuration tabbar
Huber Loss
Introduction Guide to stereo vision (6): level constraints and polar correction of fusiello method
Blogger article navigation (classified, real-time update, permanent top)
Applet global style configuration window
Introduction Guide to stereo vision (4): DLT direct linear transformation of camera calibration [recommended collection]
AUTOSAR from getting started to mastering 100 lectures (103) -dbc file format and creation details
Introduction Guide to stereo vision (3): Zhang calibration method of camera calibration [ultra detailed and worthy of collection]
随机推荐
C # draw Bezier curve with control points for lattice images and vector graphics
Illustrated network: what is gateway load balancing protocol GLBP?
Summary and Reflection on issues related to seq2seq, attention and transformer in hands-on deep learning
MPSoC QSPI flash upgrade method
.NET服务治理之限流中间件-FireflySoft.RateLimit
ROS learning 4 custom message
Solution to the problems of the 17th Zhejiang University City College Program Design Competition (synchronized competition)
2309. The best English letters with both upper and lower case
【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous
fs. Path module
Wxss template syntax
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
2311. Longest binary subsequence less than or equal to K
Golang foundation -- map, array and slice store different types of data
浅谈Label Smoothing技术
Blogger article navigation (classified, real-time update, permanent top)
驾驶证体检医院(114---2 挂对应的医院司机体检)
[code practice] [stereo matching series] Classic ad census: (5) scan line optimization
Applet data attribute method
【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用