java笔记(十二)重新理解java基本特性
2023.1.10 今年26岁了 深感对未来之恐惧
一、封装
数据被保护在类的内部,尽可能隐藏内部的细节,只有一些对外接口来与外部发生联系
public class Person {
private String name;
private int gender;
private int age;
public String getName() {
return name;
}
public String getGender() {
return gender == 0 ? "man" : "woman";
}
public void work() {
if (18 <= age && age <= 50) {
System.out.println(name + " is working very hard!");
} else {
System.out.println(name + " can't work any more!");
}
}
}
二、继承
一个类可以继承自一个父类 获得非private的属性和方法 (public protected)
三、多态
编译时多态:方法重载
运行时多态:程序中定义的对象引用所指向的具体类型在运行期间才确定(比如泛型)
public class Instrument {
public void play() {
System.out.println("Instrument is playing...");
}
}
public class Wind extends Instrument {
public void play() {
System.out.println("Wind is playing...");
}
}
public class Percussion extends Instrument {
public void play() {
System.out.println("Percussion is playing...");
}
}
public class Music {
public static void main(String[] args) {
List<Instrument> instruments = new ArrayList<>();
instruments.add(new Wind());
instruments.add(new Percussion());
for(Instrument instrument : instruments) {
instrument.play();
}
}
}
上面的代码 从静态上看 Instument对象应该调用的是自己的play方法 其实运行中调用的是子类的静态方法
四、数据类型
(1)基本类型
基本类型共8个:
boolean/1
byte/8
char/16
short/16
int/32
float/32
long/64
double/64
new Integer(1) — 创建新对象
Integer.valueOf(1) ---- 使用缓存池 得到同一个对象的引用
缓存池大小为-128 ~ 127 (java8)
在这个范围内 使用自动装箱将自动调用valueOf方法
Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true
(2)String
String是不可变的:这句话经常看到,是什么意思呢?
String内部使用char数组来存储数据 并且声明为final,且String内部不提供改变value数组的方法
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
不可变有什么好处:
1、缓存hash值
String类型的hash值不变
2、String pool
如果一个String对象被创建过了 就可以直接从String pool中引用
3、安全性
String是最常用作参数的类型 不可变性保证了传输过程中的安全
4、线程安全
String可以在多个线程中安全使用
StringBuilder可变 非线程安全
StringBuffer可变 且线程安全
String.intern()
intern()方法保证两个变量引用的是同一个对象
String s1 = new String("aaa");
String s2 = new String("aaa");
System.out.println(s1 == s2); // false
String s3 = s1.intern();
System.out.println(s1.intern() == s3); // true
如果使用String s1 = “aaa” 则它已经自动被加入到了String pool中