编程语言
首页 > 编程语言> > 备战-Java 基础

备战-Java 基础

作者:互联网

备战-Java 基础

 

        仰天大笑出门去,我辈岂是蓬蒿人。

 

简介:备战-Java 基础。

一、基本数据类型

1、Java基本数据类型

基本数据类型有8种:byte、short、int、long、float、double、boolean、char

分为4类:整数型、浮点型、布尔型、字符型。

整数型:byte、short、int、long

浮点型:float、double

布尔型:boolean

字符型:char

2、各数据类型所占字节大小

计算机的基本单位:bit .  一个bit代表一个0或1

  byte:1byte = 8bit     1个字节是8个bit

  short:2byte

  int:4byte

  long:8byte

  float:4byte

  double:8byte

  boolean:1byte

  char:2byte

boolean 只有两个值:true、false,可以使用 1 bit 来存储,但是具体大小没有明确规定。JVM 会在编译时期将 boolean 类型的数据转换为 int,使用 1 来表示 true,0 表示 false。JVM 支持 boolean 数组,但是是通过读写 byte 数组来实现的。

3、包装类型

基本类型都有对应的包装类型,基本类型与其对应的包装类型之间的赋值使用自动装箱与拆箱完成。

Integer x = 2;     // 装箱 调用了 Integer.valueOf(2)
int y = x;         // 拆箱 调用了 X.intValue()

4、缓冲池

new Integer(123) 与 Integer.valueOf(123) 的区别在于:

Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y);    // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k);   // true
View Code

valueOf() 方法的实现是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。

1 public static Integer valueOf(int i) {
2     if (i >= IntegerCache.low && i <= IntegerCache.high)
3         return IntegerCache.cache[i + (-IntegerCache.low)];
4     return new Integer(i);
5 }
View Code

在 Java 8 中,Integer 缓存池的大小默认为 -128~127。

 1 static final int low = -128;
 2 static final int high;
 3 static final Integer cache[];
 4 
 5 static {
 6     // high value may be configured by property
 7     int h = 127;
 8     String integerCacheHighPropValue =
 9         sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
10     if (integerCacheHighPropValue != null) {
11         try {
12             int i = parseInt(integerCacheHighPropValue);
13             i = Math.max(i, 127);
14             // Maximum array size is Integer.MAX_VALUE
15             h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
16         } catch( NumberFormatException nfe) {
17             // If the property cannot be parsed into an int, ignore it.
18         }
19     }
20     high = h;
21 
22     cache = new Integer[(high - low) + 1];
23     int j = low;
24     for(int k = 0; k < cache.length; k++)
25         cache[k] = new Integer(j++);
26 
27     // range [-128, 127] must be interned (JLS7 5.1.7)
28     assert IntegerCache.high >= 127;
29 }
View Code

编译器会在自动装箱过程调用 valueOf() 方法,因此多个值相同且值在缓存池范围内的 Integer 实例使用自动装箱来创建,那么就会引用相同的对象。

1 Integer m = 123;
2 Integer n = 123;
3 System.out.println(m == n); // true

基本类型对应的缓冲池如下:

在使用这些基本类型对应的包装类型时,如果该数值范围在缓冲池范围内,就可以直接使用缓冲池中的对象。

在 jdk 1.8 所有的数值类缓冲池中,Integer 的缓冲池 IntegerCache 很特殊,这个缓冲池的下界是 - 128,上界默认是 127,但是这个上界是可调的,在启动 jvm 的时候,通过 -XX:AutoBoxCacheMax=<size> 来指定这个缓冲池的大小,该选项在 JVM 初始化的时候会设定一个名为 java.lang.IntegerCache.high 系统属性,然后 IntegerCache 初始化的时候就会读取该系统属性来决定上界。

二、String

String 被声明为 final,因此它不可被继承。(Integer 等包装类也不能被继承)

在 Java 8 中,String 内部使用 char 数组存储数据。

1 public final class String
2     implements java.io.Serializable, Comparable<String>, CharSequence {
3     /** The value is used for character storage. */
4     private final char value[];
5 }

在 Java 9 之后,String 类的实现改用 byte 数组存储字符串,同时使用 coder 来标识使用了哪种编码。

1 public final class String
2     implements java.io.Serializable, Comparable<String>, CharSequence {
3     /** The value is used for character storage. */
4     private final byte[] value;
5 
6     /** The identifier of the encoding used to encode the bytes in {@code value}. */
7     private final byte coder;
8 }
View Code

value 数组被声明为 final,这意味着 value 数组初始化之后就不能再引用其它数组。并且 String 内部没有改变 value 数组的方法,因此可以保证 String 不可变。

1、String 不可变的好处

1. 可以缓存 hash 值

因为 String 的 hash 值经常被使用,例如 String 用做 HashMap 的 key。不可变的特性可以使得 hash 值也不可变,因此只需要进行一次计算。

2. String Pool 的需要

如果一个 String 对象已经被创建过了,那么就会从 String Pool 中取得引用。只有 String 是不可变的,才可能使用 String Pool。

3. 安全性

String 经常作为参数,String 不可变性可以保证参数不可变。例如在作为网络连接参数的情况下如果 String 是可变的,那么在网络连接过程中,String 被改变,改变 String 的那一方以为现在连接的是其它主机,而实际情况却不一定是。

4. 线程安全

String 不可变性天生具备线程安全,可以在多个线程中安全地使用。

2、String、StringBuffer、StringBuilder

1. 可变性

2. 线程安全

3、String Pool

字符串常量池(String Pool)保存着所有字符串字面量(literal strings),这些字面量在编译时期就确定。不仅如此,还可以使用 String 的 intern() 方法在运行过程将字符串添加到 String Pool 中。

当一个字符串调用 intern() 方法时,如果 String Pool 中已经存在一个字符串和该字符串值相等(使用 equals() 方法进行确定),那么就会返回 String Pool 中字符串的引用;否则,就会在 String Pool 中添加一个新的字符串,并返回这个新字符串的引用。

下面示例中,s1 和 s2 采用 new String() 的方式新建了两个不同字符串,而 s3 和 s4 是通过 s1.intern() 和 s2.intern() 方法取得同一个字符串引用。intern() 首先把 "aaa" 放到 String Pool 中,然后返回这个字符串引用,因此 s3 和 s4 引用的是同一个字符串。

1 String s1 = new String("aaa");
2 String s2 = new String("aaa");
3 System.out.println(s1 == s2);           // false
4 String s3 = s1.intern();
5 String s4 = s2.intern();
6 System.out.println(s3 == s4);           // true
View Code

如果是采用 "bbb" 这种字面量的形式创建字符串,会自动地将字符串放入 String Pool 中。

1 String s5 = "bbb";
2 String s6 = "bbb";
3 System.out.println(s5 == s6);  // true

在 Java 7 之前,String Pool 被放在运行时常量池中,它属于永久代。而在 Java 7,String Pool 被移到堆中。这是因为永久代的空间有限,在大量使用字符串的场景下会导致 OutOfMemoryError 错误。

4、new String("abc")

使用这种方式一共会创建两个字符串对象(前提是 String Pool 中还没有 "abc" 字符串对象)。

创建一个测试类,其 main 方法中使用这种方式来创建字符串对象。

1 public class NewStringTest {
2     public static void main(String[] args) {
3         String tjt = new String("2021-07-14");
4     }
5 }

使用 javap -verbose 进行反编译,得到以下内容:

在 Constant Pool 中,#17 存储这字符串字面量 "2021-07-14",#3 是 String Pool 的字符串对象,它指向 #17 这个字符串字面量。在 main 方法中,0: 行使用 new #2 在堆中创建一个字符串对象,并且使用 ldc #3 将 String Pool 中的字符串对象作为 String 构造函数的参数。

以下是 String 构造函数的源码,可以看到,在将一个字符串对象作为另一个字符串对象的构造函数参数时,并不会完全复制 value 数组内容,而是都会指向同一个 value 数组。

1 public String(String original) {
2     this.value = original.value;
3     this.hash = original.hash;
4 }

三、运算

1、参数传递

Java 的参数是以值传递的形式传入方法中,而不是引用传递。

以下代码中 Dog dog 的 dog 是一个指针,存储的是对象的地址。在将一个参数传入一个方法时,本质上是将对象的地址以值的方式传递到形参中。

 1 public class Dog {
 2 
 3     String name;
 4 
 5     Dog(String name) {
 6         this.name = name;
 7     }
 8 
 9     String getName() {
10         return this.name;
11     }
12 
13     void setName(String name) {
14         this.name = name;
15     }
16 
17     String getObjectAddress() {
18         return super.toString();
19     }
20 }
View Code

在方法中改变对象的字段值会改变原对象该字段值,因为引用的是同一个对象。

 1 class PassByValueExample {
 2     public static void main(String[] args) {
 3         Dog dog = new Dog("A");
 4         func(dog);
 5         System.out.println(dog.getName());          // B
 6     }
 7 
 8     private static void func(Dog dog) {
 9         dog.setName("B");
10     }
11 }
View Code

但是在方法中将指针引用了其它对象,那么此时方法里和方法外的两个指针指向了不同的对象,在一个指针改变其所指向对象的内容对另一个指针所指向的对象没有影响。

 1 public class PassByValueExample {
 2     public static void main(String[] args) {
 3         Dog dog = new Dog("A");
 4         System.out.println(dog.getObjectAddress()); // Dog@4554617c
 5         func(dog);
 6         System.out.println(dog.getObjectAddress()); // Dog@4554617c
 7         System.out.println(dog.getName());          // A
 8     }
 9 
10     private static void func(Dog dog) {
11         System.out.println(dog.getObjectAddress()); // Dog@4554617c
12         dog = new Dog("B");
13         System.out.println(dog.getObjectAddress()); // Dog@74a14482
14         System.out.println(dog.getName());          // B
15     }
16 }
View Code

2、float 与 double

Java 不能隐式执行向下转型,因为这会使得精度降低。

1.1 字面量属于 double 类型,不能直接将 1.1 直接赋值给 float 变量,因为这是向下转型。

// float f = 1.1;

1.1f 字面量才是 float 类型。

float f = 1.1f;

3、隐式类型转换

因为字面量 1 是 int 类型,它比 short 类型精度要高,因此不能隐式地将 int 类型向下转型为 short 类型。

1 short s1 = 1;
2 // s1 = s1 + 1;   // Incompatible types

但是使用 += 或者 ++ 运算符会执行隐式类型转换。

1 s1 += 1;
2 s1++;

上面的语句相当于将 s1 + 1 的计算结果进行了向下转型:

s1 = (short) (s1 + 1);

4、switch

从 Java 7 开始,可以在 switch 条件判断语句中使用 String 对象。

1 String s = "a";
2 switch (s) {
3     case "a":
4         System.out.println("aaa");
5         break;
6     case "b":
7         System.out.println("bbb");
8         break;
9 }
View Code

switch 不支持 long、float、double,是因为 switch 的设计初衷是对那些只有少数几个值的类型进行等值判断,如果值过于复杂,那么还是用 if 比较合适。

1 // long x = 111;
2 // switch (x) { // Incompatible types. Found: 'long', required: 'char, byte, short, int, Character, Byte, Short, Integer, String, or an enum'
3 //     case 111:
4 //         System.out.println(111);
5 //         break;
6 //     case 222:
7 //         System.out.println(222);
8 //         break;
9 // }
View Code

四、关键字

1、final

1. 数据

final 声明数据为常量,可以是编译时常量,也可以是在运行时被初始化后不能被改变的常量。

1 final int x = 1;
2 // x = 2;  // cannot assign value to final variable 'x'
3 final A y = new A();
4 y.a = 1;

2. 方法

final 声明方的法不能被子类重写。

private 方法隐式地被指定为 final,如果在子类中定义的方法和基类中的一个 private 方法签名相同,此时子类的方法不是重写基类方法,而是在子类中定义了一个新的方法。

3. 类

final 声明的类不允许被继承。

2、static

1. 静态变量

 1 public class A {
 2 
 3     private int x;         // 实例变量
 4     private static int y;  // 静态变量
 5 
 6     public static void main(String[] args) {
 7         // int x = A.x;  // Non-static field 'x' cannot be referenced from a static context
 8         A a = new A();
 9         int x = a.x;
10         int y = A.y;
11     }
12 }
View Code

2. 静态方法

静态方法在类加载的时候就存在了,它不依赖于任何实例。所以静态方法必须有实现,也就是说它不能是抽象方法。

1 public abstract class A {
2     public static void func1(){
3     }
4     // public abstract static void func2();  // Illegal combination of modifiers: 'abstract' and 'static'
5 }

只能访问所属类的静态字段和静态方法,方法中不能有 this 和 super 关键字,因为这两个关键字与具体对象关联。

 1 public class A {
 2 
 3     private static int x;
 4     private int y;
 5 
 6     public static void func1(){
 7         int a = x;
 8         // int b = y;  // Non-static field 'y' cannot be referenced from a static context
 9         // int b = this.y;     // 'A.this' cannot be referenced from a static context
10     }
11 }
View Code

3. 静态语句块

静态语句块在类初始化时运行一次。

 1 public class A {
 2     static {
 3         System.out.println("123");
 4     }
 5 
 6     public static void main(String[] args) {
 7         A a1 = new A();
 8         A a2 = new A();
 9     }
10 }
View Code

4. 静态内部类

非静态内部类依赖于外部类的实例,也就是说需要先创建外部类实例,才能用这个实例去创建非静态内部类。而静态内部类不需要。

 1 public class OuterClass {
 2 
 3     class InnerClass {
 4     // 非静态内部类
 5     }
 6 
 7     static class StaticInnerClass {
 8      // 静态内部类
 9     }
10 
11     public static void main(String[] args) {
12         // InnerClass innerClass = new InnerClass(); // 'OuterClass.this' cannot be referenced from a static context
13         OuterClass outerClass = new OuterClass();
14         InnerClass innerClass = outerClass.new InnerClass();
15         StaticInnerClass staticInnerClass = new StaticInnerClass();
16     }
17 }
View Code

同时,静态内部类不能访问外部类的非静态的变量和方法。

5. 静态导包

在使用静态变量和方法时不用再指明 ClassName,从而简化代码,但可读性大大降低。

import static com.xxx.ClassName.*

6. 初始化顺序

静态变量和静态语句块优先于实例变量和普通语句块,静态变量和静态语句块的初始化顺序取决于它们在代码中的顺序。

五、Object 通用方法

 1 public native int hashCode()
 2 
 3 public boolean equals(Object obj)
 4 
 5 protected native Object clone() throws CloneNotSupportedException
 6 
 7 public String toString()
 8 
 9 public final native Class<?> getClass()
10 
11 protected void finalize() throws Throwable {}
12 
13 public final native void notify()
14 
15 public final native void notifyAll()
16 
17 public final native void wait(long timeout) throws InterruptedException
18 
19 public final void wait(long timeout, int nanos) throws InterruptedException
20 
21 public final void wait() throws InterruptedException
View Code

1、equals()

1. 等价关系

两个对象具有等价关系,需要满足以下五个条件:

Ⅰ 自反性

x.equals(x); // true

Ⅱ 对称性

x.equals(y) == y.equals(x); // true

Ⅲ 传递性

1 if (x.equals(y) && y.equals(z))
2     x.equals(z); // true;

Ⅳ 一致性

多次调用 equals() 方法结果不变

x.equals(y) == x.equals(y); // true

Ⅴ 与 null 的比较

对任何不是 null 的对象 x 调用 x.equals(null) 结果都为 false

x.equals(null); // false;

2. 等价与相等

1 Integer x = new Integer(1);
2 Integer y = new Integer(1);
3 System.out.println(x.equals(y)); // true
4 System.out.println(x == y);      // false
View Code

3. 实现

 1 public class EqualExample {
 2 
 3     private int x;
 4     private int y;
 5     private int z;
 6 
 7     public EqualExample(int x, int y, int z) {
 8         this.x = x;
 9         this.y = y;
10         this.z = z;
11     }
12 
13     @Override
14     public boolean equals(Object o) {
15         if (this == o) return true;
16         if (o == null || getClass() != o.getClass()) return false;
17 
18         EqualExample that = (EqualExample) o;
19 
20         if (x != that.x) return false;
21         if (y != that.y) return false;
22         return z == that.z;
23     }
24 }
View Code

2、hashCode()

hashCode() 返回哈希值,而 equals() 是用来判断两个对象是否等价。等价的两个对象散列值一定相同,但是散列值相同的两个对象不一定等价,这是因为计算哈希值具有随机性,两个值不同的对象可能计算出相同的哈希值。

在覆盖 equals() 方法时应当总是覆盖 hashCode() 方法,保证等价的两个对象哈希值也相等。

HashSet 和 HashMap 等集合类使用了 hashCode() 方法来计算对象应该存储的位置,因此要将对象添加到这些集合类中,需要让对应的类实现 hashCode() 方法。

下面的代码中,新建了两个等价的对象,并将它们添加到 HashSet 中。我们希望将这两个对象当成一样的,只在集合中添加一个对象。但是 EqualExample 没有实现 hashCode() 方法,因此这两个对象的哈希值是不同的,最终导致集合添加了两个等价的对象。

1 EqualExample e1 = new EqualExample(1, 1, 1);
2 EqualExample e2 = new EqualExample(1, 1, 1);
3 System.out.println(e1.equals(e2)); // true
4 HashSet<EqualExample> set = new HashSet<>();
5 set.add(e1);
6 set.add(e2);
7 System.out.println(set.size());   // 2
View Code

理想的哈希函数应当具有均匀性,即不相等的对象应当均匀分布到所有可能的哈希值上。这就要求了哈希函数要把所有域的值都考虑进来。可以将每个域都当成 R 进制的某一位,然后组成一个 R 进制的整数。

R 一般取 31,因为它是一个奇素数,如果是偶数的话,当出现乘法溢出,信息就会丢失,因为与 2 相乘相当于向左移一位,最左边的位丢失。并且一个数与 31 相乘可以转换成移位和减法:31*x == (x<<5)-x,编译器会自动进行这个优化。

1 @Override
2 public int hashCode() {
3     int result = 17;
4     result = 31 * result + x;
5     result = 31 * result + y;
6     result = 31 * result + z;
7     return result;
8 }
View Code

3、toString()

默认返回 ToStringExample@4554617c 这种形式,其中 @ 后面的数值为散列码的无符号十六进制表示。

1 public class ToStringExample {
2 
3     private int number;
4 
5     public ToStringExample(int number) {
6         this.number = number;
7     }
8 }
View Code
1 ToStringExample example = new ToStringExample(123);
2 System.out.println(example.toString());  // ToStringExample@4554617c

4、clone()

1. cloneable

clone() 是 Object 的 protected 方法,它不是 public,一个类不显示去重写 clone(),其它类就不能直接去调用该类实例的 clone() 方法。

1 public class CloneExample {
2     private int a;
3     private int b;
4 }
1 CloneExample e1 = new CloneExample();
2 // CloneExample e2 = e1.clone(); // 'clone()' has protected access in 'java.lang.Object'

重写 clone() 得到以下实现:

1 public class CloneExample {
2     private int a;
3     private int b;
4 
5     @Override
6     public CloneExample clone() throws CloneNotSupportedException {
7         return (CloneExample)super.clone();
8     }
9 }
View Code
1 CloneExample e1 = new CloneExample();
2 try {
3     CloneExample e2 = e1.clone();
4 } catch (CloneNotSupportedException e) {
5     e.printStackTrace();  // java.lang.CloneNotSupportedException: CloneExample
6 
7 }

以上抛出了 CloneNotSupportedException,这是因为 CloneExample 没有实现 Cloneable 接口。

应该注意的是,clone() 方法并不是 Cloneable 接口的方法,而是 Object 的一个 protected 方法。Cloneable 接口只是规定,如果一个类没有实现 Cloneable 接口又调用了 clone() 方法,就会抛出 CloneNotSupportedException。

1 public class CloneExample implements Cloneable {
2     private int a;
3     private int b;
4 
5     @Override
6     public Object clone() throws CloneNotSupportedException {
7         return super.clone();
8     }
9 }
View Code

2. 浅拷贝

拷贝对象和原始对象的引用类型引用同一个对象。

 1 public class ShallowCloneExample implements Cloneable {
 2 
 3     private int[] arr;
 4 
 5     public ShallowCloneExample() {
 6         arr = new int[10];
 7         for (int i = 0; i < arr.length; i++) {
 8             arr[i] = i;
 9         }
10     }
11 
12     public void set(int index, int value) {
13         arr[index] = value;
14     }
15 
16     public int get(int index) {
17         return arr[index];
18     }
19 
20     @Override
21     protected ShallowCloneExample clone() throws CloneNotSupportedException {
22         return (ShallowCloneExample) super.clone();
23     }
24 }
View Code
1 ShallowCloneExample e1 = new ShallowCloneExample();
2 ShallowCloneExample e2 = null;
3 try {
4     e2 = e1.clone();
5 } catch (CloneNotSupportedException e) {
6     e.printStackTrace();
7 }
8 e1.set(2, 222);
9 System.out.println(e2.get(2)); // 222
View Code

3. 深拷贝

拷贝对象和原始对象的引用类型引用不同对象。

 1 public class DeepCloneExample implements Cloneable {
 2 
 3     private int[] arr;
 4 
 5     public DeepCloneExample() {
 6         arr = new int[10];
 7         for (int i = 0; i < arr.length; i++) {
 8             arr[i] = i;
 9         }
10     }
11 
12     public void set(int index, int value) {
13         arr[index] = value;
14     }
15 
16     public int get(int index) {
17         return arr[index];
18     }
19 
20     @Override
21     protected DeepCloneExample clone() throws CloneNotSupportedException {
22         DeepCloneExample result = (DeepCloneExample) super.clone();
23         result.arr = new int[arr.length];
24         for (int i = 0; i < arr.length; i++) {
25             result.arr[i] = arr[i];
26         }
27         return result;
28     }
29 }
View Code
1 DeepCloneExample e1 = new DeepCloneExample();
2 DeepCloneExample e2 = null;
3 try {
4     e2 = e1.clone();
5 } catch (CloneNotSupportedException e) {
6     e.printStackTrace();
7 }
8 e1.set(2, 222);
9 System.out.println(e2.get(2)); // 2
View Code

4. clone() 的替代方案

使用 clone() 方法来拷贝一个对象即复杂又有风险,它会抛出异常,并且还需要类型转换。Effective Java 书上讲到,最好不要去使用 clone(),可以使用拷贝构造函数或者拷贝工厂来拷贝一个对象。

 1 public class CloneConstructorExample {
 2 
 3     private int[] arr;
 4 
 5     public CloneConstructorExample() {
 6         arr = new int[10];
 7         for (int i = 0; i < arr.length; i++) {
 8             arr[i] = i;
 9         }
10     }
11 
12     public CloneConstructorExample(CloneConstructorExample original) {
13         arr = new int[original.arr.length];
14         for (int i = 0; i < original.arr.length; i++) {
15             arr[i] = original.arr[i];
16         }
17     }
18 
19     public void set(int index, int value) {
20         arr[index] = value;
21     }
22 
23     public int get(int index) {
24         return arr[index];
25     }
26 }
View Code
1 CloneConstructorExample e1 = new CloneConstructorExample();
2 CloneConstructorExample e2 = new CloneConstructorExample(e1);
3 e1.set(2, 222);
4 System.out.println(e2.get(2)); // 2

六、继承

1、访问权限

Java 中有三个访问权限修饰符:private、protected 以及 public,如果不加访问修饰符,表示包级可见。

可以对类或类中的成员(字段和方法)加上访问修饰符。

protected 用于修饰成员,表示在继承体系中成员对于子类可见,但是这个访问修饰符对于类没有意义。

设计良好的模块会隐藏所有的实现细节,把它的 API 与它的实现清晰地隔离开来。模块之间只通过它们的 API 进行通信,一个模块不需要知道其他模块的内部工作情况,这个概念被称为信息隐藏或封装。因此访问权限应当尽可能地使每个类或者成员不被外界访问。

如果子类的方法重写了父类的方法,那么子类中该方法的访问级别不允许低于父类的访问级别。这是为了确保可以使用父类实例的地方都可以使用子类实例去代替,也就是确保满足里氏替换原则。

字段决不能是公有的,因为这么做的话就失去了对这个字段修改行为的控制,客户端可以对其随意修改。例如下面的例子中,AccessExample 拥有 id 公有字段,如果在某个时刻,我们想要使用 int 存储 id 字段,那么就需要修改所有的客户端代码。

1 public class AccessExample {
2     public String id;
3 }

可以使用公有的 getter 和 setter 方法来替换公有字段,这样的话就可以控制对字段的修改行为。

 1 public class AccessExample {
 2 
 3     private int id;
 4 
 5     public String getId() {
 6         return id + "";
 7     }
 8 
 9     public void setId(String id) {
10         this.id = Integer.valueOf(id);
11     }
12 }
View Code

但是也有例外,如果是包级私有的类或者私有的嵌套类,那么直接暴露成员不会有特别大的影响。

 1 public class AccessWithInnerClassExample {
 2 
 3     private class InnerClass {
 4         int x;
 5     }
 6 
 7     private InnerClass innerClass;
 8 
 9     public AccessWithInnerClassExample() {
10         innerClass = new InnerClass();
11     }
12 
13     public int getValue() {
14         return innerClass.x;  // 直接访问
15     }
16 }
View Code

2、抽象类与接口

1. 抽象类

抽象类和抽象方法都使用 abstract 关键字进行声明。如果一个类中包含抽象方法,那么这个类必须声明为抽象类。

抽象类和普通类最大的区别是,抽象类不能被实例化,只能被继承。

 1 // 抽象类
 2 public abstract class AbstractClassExample {
 3 
 4     protected int x;
 5     private int y;
 6 
 7     public abstract void func1();
 8 
 9     public void func2() {
10         System.out.println("func2");
11     }
12 }
View Code
1 // 普通类
2 public class AbstractExtendClassExample extends AbstractClassExample {
3     @Override
4     public void func1() {
5         System.out.println("func1");
6     }
7 }
View Code
1 // AbstractClassExample ac1 = new AbstractClassExample(); // 'AbstractClassExample' is abstract; cannot be instantiated
2 AbstractClassExample ac2 = new AbstractExtendClassExample();
3 ac2.func1();

2. 接口

接口是抽象类的延伸,在 Java 8 之前,它可以看成是一个完全抽象的类,也就是说它不能有任何的方法实现。

从 Java 8 开始,接口也可以拥有默认的方法实现,这是因为不支持默认方法的接口的维护成本太高了。在 Java 8 之前,如果一个接口想要添加新的方法,那么要修改所有实现了该接口的类,让它们都实现新增的方法。

接口的成员(字段 + 方法)默认都是 public 的,并且不允许定义为 private 或者 protected。从 Java 9 开始,允许将方法定义为 private,这样就能定义某些复用的代码又不会把方法暴露出去。

接口的字段默认都是 static 和 final 的。

 1 public interface InterfaceExample {
 2 
 3     void func1();
 4 
 5     default void func2(){
 6         System.out.println("func2");
 7     }
 8 
 9     int x = 123;
10     // int y;               // Variable 'y' might not have been initialized
11     public int z = 0;       // Modifier 'public' is redundant for interface fields
12     // private int k = 0;   // Modifier 'private' not allowed here
13     // protected int l = 0; // Modifier 'protected' not allowed here
14     // private void fun3(); // Modifier 'private' not allowed here
15 }
View Code
1 public class InterfaceImplementExample implements InterfaceExample {
2     @Override
3     public void func1() {
4         System.out.println("func1");
5     }
6 }
View Code
1 // InterfaceExample ie1 = new InterfaceExample(); // 'InterfaceExample' is abstract; cannot be instantiated
2 InterfaceExample ie2 = new InterfaceImplementExample();
3 ie2.func1();
4 System.out.println(InterfaceExample.x);

3. 比较

4. 使用选择

使用接口:

使用抽象类:

在很多情况下,接口优先于抽象类。因为接口没有抽象类严格的类层次结构要求,可以灵活地为一个类添加行为。并且从 Java 8 开始,接口也可以有默认的方法实现,使得修改接口的成本也变的很低。

3、super

 1 // 父类
 2 public class SuperExample {
 3 
 4     protected int x;
 5     protected int y;
 6 
 7     public SuperExample(int x, int y) {
 8         this.x = x;
 9         this.y = y;
10     }
11 
12     public void func() {
13         System.out.println("SuperExample.func()");
14     }
15 }
View Code
 1 // 子类继承父类
 2 public class SuperExtendExample extends SuperExample {
 3 
 4     private int z;
 5 
 6     public SuperExtendExample(int x, int y, int z) {
 7         super(x, y);
 8         this.z = z;
 9     }
10 
11     @Override
12     public void func() {
13         super.func();
14         System.out.println("SuperExtendExample.func()");
15     }
16 }
View Code

4、重写与重载

1. 重写(Override)

存在于继承体系中,指子类实现了一个与父类在方法声明上完全相同的一个方法。

为了满足里式替换原则,重写有以下三个限制:

使用 @Override 注解,可以让编译器帮忙检查是否满足上面的三个限制条件。

下面的示例中,SubClass 为 SuperClass 的子类,SubClass 重写了 SuperClass 的 func() 方法。其中:

 1 class SuperClass {
 2     protected List<Integer> func() throws Throwable {
 3         return new ArrayList<>();
 4     }
 5 }
 6 
 7 class SubClass extends SuperClass {
 8     @Override
 9     public ArrayList<Integer> func() throws Exception {
10         return new ArrayList<>();
11     }
12 }
View Code

在调用一个方法时,先从本类中查找看是否有对应的方法,如果没有再到父类中查看,看是否从父类继承来。否则就要对参数进行转型,转成父类之后看是否有对应的方法。总的来说,方法调用的优先级为:

 1 /*
 2     A
 3     |
 4     B
 5     |
 6     C
 7     |
 8     D
 9  */
10 
11 
12 class A {
13 
14     public void show(A obj) {
15         System.out.println("A.show(A)");
16     }
17 
18     public void show(C obj) {
19         System.out.println("A.show(C)");
20     }
21 }
22 
23 class B extends A {
24 
25     @Override
26     public void show(A obj) {
27         System.out.println("B.show(A)");
28     }
29 }
30 
31 class C extends B {
32 }
33 
34 class D extends C {
35 }
View Code
 1 public static void main(String[] args) {
 2 
 3     A a = new A();
 4     B b = new B();
 5     C c = new C();
 6     D d = new D();
 7 
 8     // 在 A 中存在 show(A obj),直接调用
 9     a.show(a); // A.show(A)
10     // 在 A 中不存在 show(B obj),将 B 转型成其父类 A
11     a.show(b); // A.show(A)
12     // 在 B 中存在从 A 继承来的 show(C obj),直接调用
13     b.show(c); // A.show(C)
14     // 在 B 中不存在 show(D obj),但是存在从 A 继承来的 show(C obj),将 D 转型成其父类 C
15     b.show(d); // A.show(C)
16 
17     // 引用的还是 B 对象,所以 ba 和 b 的调用结果一样
18     A ba = new B();
19     ba.show(c); // A.show(C)
20     ba.show(d); // A.show(C)
21 }
View Code

2. 重载(Overload)

存在于同一个类中,指一个方法与已经存在的方法名称上相同,但是参数类型、个数、顺序至少有一个不同。

应该注意的是,返回值不同,其它都相同不算是重载。

1 class OverloadingExample {
2     public void show(int x) {
3         System.out.println(x);
4     }
5 
6     public void show(int x, String y) {
7         System.out.println(x + " " + y);
8     }
9 }
View Code
1 public static void main(String[] args) {
2     OverloadingExample example = new OverloadingExample();
3     example.show(1);
4     example.show(1, "2");
5 }
View Code

七、反射

每个类都有一个 Class 对象,包含了与类有关的信息。当编译一个新类时,会产生一个同名的 .class 文件,该文件内容保存着 Class 对象。

类加载相当于 Class 对象的加载,类在第一次使用时才动态加载到 JVM 中。也可以使用 Class.forName("com.mysql.jdbc.Driver") 这种方式来控制类的加载,该方法会返回一个 Class 对象。

反射可以提供运行时的类信息,并且这个类可以在运行时才加载进来,甚至在编译时期该类的 .class 不存在也可以加载进来。

Class 和 java.lang.reflect 一起对反射提供了支持,java.lang.reflect 类库主要包含了以下三个类:

反射的优点:

反射的缺点:

尽管反射非常强大,但也不能滥用。如果一个功能可以不用反射完成,那么最好就不用。在我们使用反射技术时,下面几条内容应该牢记于心。

八、异常

Throwable 可以用来表示任何可以作为异常抛出的类,分为两种: Error 和 Exception。其中 Error 用来表示 JVM 无法处理的错误,Exception 分为两种:

九、泛型

泛型,即“参数化类型”。一提到参数,最熟悉的就是定义方法时有形参,然后调用此方法时传递实参。那么参数化类型怎么理解呢?顾名思义,就是将类型由原来的具体的类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可以称之为类型形参),然后在使用/调用时传入具体的类型(类型实参)。

泛型的本质是为了参数化类型(在不创建新的类型的情况下,通过泛型指定的不同类型来控制形参具体限制的类型)。也就是说在泛型使用过程中,操作的数据类型被指定为一个参数,这种参数类型可以用在类、接口和方法中,分别被称为泛型类、泛型接口、泛型方法。

1     // T stands for "Type"
2     private T t;
3     public void set(T t) { this.t = t; }
4     public T get() { return t; }
5 }

十、注解

Java 注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。

 1 package com.tjt.springmvc;
 2 
 3 
 4 import java.lang.annotation.*;
 5 
 6 
 7 /**
 8  * @MyController 自定义注解类
 9  *
10  * @@Target(ElementType.TYPE)
11  * 表示该注解可以作用在类上;
12  *
13  * @Retention(RetentionPolicy.RUNTIME)
14  * 表示该注解会在class 字节码文件中存在,在运行时可以通过反射获取到
15  *
16  * @Documented
17  * 标记注解,表示可以生成文档
18  */
19 @Target(ElementType.TYPE)
20 @Retention(RetentionPolicy.RUNTIME)
21 @Documented
22 public @interface MyController {
23 
24     /**
25      * public class MyController
26      * 把 class 替换成 @interface 该类即成为注解类
27      */
28 
29     /**
30      * 为Controller 注册别名
31      * @return
32      */
33     String value() default "";
34 
35 }
View Code

十一、特性

1、Java 与 C++ 的区别

2、JRE & JDK

 

 

 

        仰天大笑出门去

我辈岂是蓬蒿人

 

  

 

 

标签:Java,String,int,class,基础,备战,new,public,View
来源: https://www.cnblogs.com/taojietaoge/p/15012003.html