目录
1. this的含义
2. this的用法
2.1 调用属性
2.2 调用普通方法
2.3 调用构造方法
1. this的含义
this代表的是当前类对象
2. this的用法
2.1 调用属性
2.2 调用普通方法
在一个类中直接使用本类中的方法加不加this,一个意思,暂时看不出区别,后期在继承中做区别。
2.3 调用构造方法
例子:
数组长度一旦确定,不能再更改,如果需要更改,则必须重新创建新数组。
设计一个类MyArray
具备:可以保存多个字符串、可以查看有多少个字符串、可以检索所有的字符串。
类{
属性---数据
数组 String [] datas
长度 int size
方法 ---功能
add(String str)
size()
each()
}
代码实现:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99package com.njwbhz.february.week3.part0218; /** * @author FairyKunKun * @since 2022/2/18 */ public class MyArray { //可以保存多个字符串 //可以查看有多少个字符串 //可以检索所有的字符串 //属性 //数组 private String [] datas; //长度 private int size; //方法 public MyArray() {//默认10个 // datas = new String[10]; // MyArray(10); //本义是调用下面的构造器 //构造其余构造器之间的调用通过this调用 //语法 //this() + 参数列表 this (10); //构造器与构造期之间的调用只能放到第一行 } public MyArray (int length) { datas = new String[length]; } //添加 public void add (String string) { //添加一个数据 //满了 if (size == datas.length) { String [] newDatas = new String[(int)(datas.length * 1.5)]; System.arraycopy(datas , 0 , newDatas , 0 , datas.length); datas = newDatas; //满了 } datas[size++] = string; } //遍历 public void each () { System.out.println("把数据输出出来。。。"); for (int i = 0 ; i < size ; i++){ System.out.print(datas[i] + "t"); } } // public String[] getDatas() { // return datas; // } // public void setDatas(String[] datas) { // this.datas = datas; // } public int getSize() { return size; } // public void setSize(int size) { // this.size = size; // } /* 狭义的封装(出于安全考虑) 对数据的封装 广义的封装(出于方便考虑) 包含功能的封装 method1(){ 代码1; 代码2; .. } ABC类都会用到这一块代码 程序员说,把这块功能封装一下吧 X类 属性 构造方法 普通方法 */ //得到数组 public String[] getDatas() { return datas; } }
代码测试:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34package com.njwbhz.february.week3.part0218; /** * @author FairyKunKun * @since 2022/2/18 */ public class TestMyArray { public static void main(String[] args) { MyArray myArray = new MyArray(); myArray.add("a"); myArray.add("ab"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("awde"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); myArray.add("a"); System.out.println(myArray.getSize()); myArray.each(); } }
最后
以上就是小巧薯片最近收集整理的关于【JAVA语言面向对象】(13)this的使用的全部内容,更多相关【JAVA语言面向对象】(13)this内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复