当前位置:网站首页>[kotlin learning] classes, objects and interfaces - define class inheritance structure
[kotlin learning] classes, objects and interfaces - define class inheritance structure
2022-07-03 09:17:00 【Android old monkey】
Define class inheritance structure
kotlin The interface
The following figure declares a property named click The interface of the single abstract method , All non abstract classes that implement the interface should provide the implementation of this method

kotlin Use a colon instead of extends and implements keyword , and java equally , A class can implement multiple interfaces, but can only inherit one class

stay kotlin Use in override Modifiers are mandatory , This will avoid accidental rewriting caused by writing out the implementation method first and adding abstract methods
Interface methods can have a default implementation , stay Java8 You need to mark on such an implementation default keyword , and kotlin No special notes , You only need to provide a method body

Now define another one Focusable Interface , It also implements a showOff Method
When your class implements these two interfaces , No implementation will be used , The compiler will ask you to provide your own implementation

modify MyButton The categories are as follows

To call an inherited implementation , have access to super keyword , But the syntax for choosing a particular implementation is different , stay java Medium is Clickable.super.showOff(), And in the kotlin Medium is super< Clickable>.showOff()
stay Java Implement the interface containing the method body
Kotlin1.0 In order to Java 6 Designed for the purpose , Default methods in interfaces are not supported , therefore It compiles each interface with default methods into a combination of an ordinary interface and a class that takes the method body as a static function .
open、final、abstract Modifier : The default is final
stay Java Allows you to create subclasses of any class and override any method , Unless you explicitly call final Key words to mark . Modifying the base class will lead to incorrect behavior of subclasses , The so-called vulnerability is this kind of problem , Because the modification of the base class code no longer meets the assumptions in its subclasses . Any modification of the base class may lead to changes in the behavior of subclasses beyond it .
stay java The default for both classes and methods in open Of , stay kotlin The default for both classes and methods in final Of .
If you want to allow the creation of subclasses of a class , Use open Modifier to identify this class , Also add... To every property and method that can be overridden open Modifier

If you override a member of a base class or interface , The overridden member also defaults to open Of , If you want to prevent subclasses of your class from overriding your implementation , You can explicitly mark overridden members as final

open Class and intelligent transformation
Class default final It makes intelligent transformation possible in a large number of scenes , We mentioned earlier that intelligent transformation can only work on variables that have not changed after type checking , For a class , This means that intelligent transformation can only be carried out in val Type and no custom accessor is used on the class attribute . This premise means that the attribute must be final Of , Otherwise, taking a stake in a subclass can override properties and define a custom accessor, which will break the key premise of intelligent transformation
stay kotlin in , You can declare a class as abstruct Of , This class cannot be instantiated . It usually contains some abstract members that are not implemented and must be overridden in subclasses . Abstract members are always open Of , So you don't need to explicitly use open

| Access modifier in class | Related members | Commentary |
|---|---|---|
| final | Can't be rewritten | By default, members in the class use |
| open | Can be rewritten | It needs to be made clear |
| abstruct | Must be rewritten | Can only be used in abstract classes , Abstract members cannot have implementations |
| override | Override a member of a parent class or interface | If it doesn't work final indicate . Overridden members are open by default |
Visibility modifier : The default is public
kotlin neutralization java Almost the same as , But the default is different ,kotlin The default is public.
And a new modifier is provided :internal( Visible only inside the module ), A module is a set of modules compiled together kotlin file , It could be a IDEA modular 、 A set of use calls Ant Files compiled by tasks, etc .
kotlin It is also allowed to use... In top-level declarations private, Including class 、 function 、 attribute , These declarations will only be visible in the file in which they are declared
| Visibility modifier | Members of the class | Top level statement |
|---|---|---|
| public | Everywhere you can see | Everywhere you can see |
| internal | You can see... In the module | You can see... In the module |
| protected | See in subclass | nothing |
| private | Class | It can be seen in the document |

kotlin Prohibition from public function giveSpeech To reference low visibility types TalkativeButton(internal). General rules : The basic type of the class and all classes used in the type parameter list , Or the signature of the function has the same visibility as the class or function itself .
Be careful protected Modifiers in java and kotlin Different , stay java Can be accessed from the same package protected member , but kotlin Don't allow , stay kotlin Only its members are allowed to be visible in the class and its subclasses
Note that the extension function of a class cannot access its private and protected member
kotlin Visibility modifiers and java
kotlin Of public、protected、private The modifier is compiled into java Bytecode will be reserved . The only exception is private class : This situation will be compiled into a package private declaration .
A module usually consists of multiple packages , And different modules may contain declarations from the same package , therefore internal The modifier becomes... In bytecode public, This explains why sometimes we can start from java Code that you can't access from kotlin Something to visit in
Class internal Member names will be destroyed
stay kotlin An external class in cannot see its interior / In nested classes private member
Inner classes and nested classes : The default is nested classes
stay kotlin You can declare a class in another class , This is useful when encapsulating a helper class or putting some code close to where it is used . But it's different from Java,kotlin Nested classes cannot access instances of external classes , Unless you specifically ask .
example Declare a view that contains serializable state



You can see that we are trying to return an implementation State Interface ButonState, stay kotlin Medium feasible , stay java If you write in this way, you will report an error , Because in java in ButtonState Class implicitly stores its external MyButton References to , and MyButton Can't be serialized , Its reference breaks ButtonState Serialization . To fix it, you need to declare ButtonState Class is static, The nested class will delete the implicit reference of the class surrounding it .kotlin Nested classes and without explicit modifiers in java Medium static Nested classes are the same . To turn it into an internal class to hold a reference to an external class, use inner Modifier
| class A In another class B Statement | stay Java in | stay Kotlin in |
|---|---|---|
| Nested class ( Do not store references to external classes ) | static class A | class A |
| Inner class ( Store references to external classes ) | class A | inner class A |
stay kotlin The syntax of referencing external class instances in is also similar to java Different , Need to use [email protected] from Inner Such access Outer class

Sealing class : Define a restricted class inheritance structure
Review in kotlin Examples in the basic chapter

stay when It is convenient to handle all possible subclasses in expressions , But one must be provided else Branch to handle situations where no other branch can match . It's inconvenient to always have to add a default Branch , More importantly, if you add a new subclass , The compiler can't find that something has changed , If you forget to add new branches, there will be * * bug.
kotlin This provides a solution :sealed class .
Add... For the parent class sealed Modifier , Make strict restrictions on possible subclasses , All direct subclasses must be nested in the parent class

A sealed class cannot have subclasses outside a class , If you are in the when All... Are processed in the expression sealed Subclasses of classes , There is no need to provide a default Branch .sealed The class implied by the modifier is a open class , There is no need to explicitly add open Modifier .
We cannot declare sealed Interface , Because the compiler cannot guarantee that no one can java Implement this interface in the code
stay kotlin1.0 in ,sealed The function is quite strict , All subclasses must be nested , And subclasses cannot be created as data class .1.1 It removes these restrictions and allows you to define... Anywhere in the same file sealed Subclasses of classes
边栏推荐
- 传统办公模式的“助推器”,搭建OA办公系统,原来就这么简单!
- LeetCode 871. Minimum refueling times
- Temper cattle ranking problem
- LeetCode 532. K-diff number pairs in array
- Severity code description the project file line prohibits the display of status error c2440 "initialization": unable to convert from "const char [31]" to "char *"
- The less successful implementation and lessons of RESNET
- [point cloud processing paper crazy reading classic version 12] - foldingnet: point cloud auto encoder via deep grid deformation
- [point cloud processing paper crazy reading frontier edition 13] - gapnet: graph attention based point neural network for exploring local feature
- Save the drama shortage, programmers' favorite high-score American drama TOP10
- Overview of database system
猜你喜欢
![[point cloud processing paper crazy reading classic version 10] - pointcnn: revolution on x-transformed points](/img/c1/045ca010b212376dc3e5532d25c654.png)
[point cloud processing paper crazy reading classic version 10] - pointcnn: revolution on x-transformed points

LeetCode 532. 数组中的 k-diff 数对
![[point cloud processing paper crazy reading frontier version 8] - pointview gcn: 3D shape classification with multi view point clouds](/img/ee/3286e76797a75c0f999c728fd2b555.png)
[point cloud processing paper crazy reading frontier version 8] - pointview gcn: 3D shape classification with multi view point clouds

低代码起势,这款信息管理系统开发神器,你值得拥有!

Find the combination number acwing 886 Find the combination number II

Digital management medium + low code, jnpf opens a new engine for enterprise digital transformation

Temper cattle ranking problem

Redis learning (I)

Computing level network notes

AcWing 787. 归并排序(模板)
随机推荐
AcWing 788. Number of pairs in reverse order
Use of sort command in shell
Shell script kills the process according to the port number
Tree DP acwing 285 A dance without a boss
Digital management medium + low code, jnpf opens a new engine for enterprise digital transformation
2022-1-6 Niuke net brush sword finger offer
【点云处理之论文狂读前沿版12】—— Adaptive Graph Convolution for Point Cloud Analysis
Beego learning - Tencent cloud upload pictures
On a un nom en commun, maître XX.
C language programming specification
LeetCode 508. The most frequent subtree elements and
LeetCode 438. Find all letter ectopic words in the string
【点云处理之论文狂读前沿版10】—— MVTN: Multi-View Transformation Network for 3D Shape Recognition
【点云处理之论文狂读前沿版11】—— Unsupervised Point Cloud Pre-training via Occlusion Completion
浅谈企业信息化建设
We have a common name, XX Gong
[untitled] use of cmake
传统企业数字化转型需要经过哪几个阶段?
[point cloud processing paper crazy reading classic version 12] - foldingnet: point cloud auto encoder via deep grid deformation
Data mining 2021-4-27 class notes