类与对象
public class Demo {
public static void main(String[] args) {
// 创建person对象
Person person = new Person();
person.name = "张三";
person.age = 18;
person.tell();
}
}
// 定义Person类
class Person {
String name;
int age;
public void tell() {
System.out.println("姓名:" + name + ",年龄:" + age);
}
}
内存分析
Person person = new Person();
栈内存 | 堆内存 |
---|---|
person | name:null age:0 |
person.name = "张三";
person.age = 18;
栈内存 | 堆内存 |
---|---|
person | name:张三 age:18 |
成员属性封装
public class Demo {
public static void main(String[] args) {
Person person = new Person();
person.setName("张三");
person.setAge(-5);
System.out.println(person.getName());
System.out.println(person.getAge());
}
}
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name2) {
name = name2;
}
public int getAge() {
return age;
}
public void setAge(int age2) {
if(age2 < 0) {
age = 1;
}else {
age = age2;
}
}
}
构造方法和匿名对象
如果我们手动在某个类中定义了一个有参数的构造函数,那么这个默认的无参构造函数就不会自动添加了。需要手动创建!
成员变量的默认值,如int -> 0,Integer -> null
public class Demo {
public static void main(String[] args) {
Person person1 = new Person();
person1.tell();
Person person2 = new Person("张三", 18);
person2.tell();
// 匿名对象
new Person("李四",19).tell();
}
}
class Person {
String name;
int age;
// 构造方法1
public Person() {
}
// 构造方法2
public Person(String name2, int age2) {
name = name2;
age = age2;
}
// 普通方法
public void tell() {
System.out.println("姓名:" + name + ",年龄:" + age);
}
}
Java中只有值传递
public class Demo {
public static void main(String[] args) throws Exception {
Person person = new Person();
person.setName("张三");
fun(person);
System.out.println(person.getName());
}
public static void fun(Person person) {
person = new Person();
person.setName("李四");
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
this的使用
public class Demo {
public static void main(String[] args) {
new Person().tell();
new Person("张三").tell();
new Person("李四",19).tell();
}
}
class Person {
// 属性
private String name;
private int age;
// 构造方法
public Person() {
this("无名");
}
public Person(String name) {
this(name, 1);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// get set 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// 普通方法
public void tell() {
System.out.println("姓名:" + this.name + ",年龄:" + this.age);
}
}
static关键字
Java中共有三种变量,分别是类变量、成员变量和局部变量。他们分别存放在JVM的方法区、堆内存和栈内存中
static属性
public class Demo {
public static void main(String[] args) {
System.out.println(Person.country);
new Person("张三", 18).tell();
new Person("李四",19).tell();
}
}
class Person {
static String country = "中国";
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void tell() {
System.out.println("姓名:" + name + ",年龄:" + age + ",国籍:" + country);
}
}
static方法
public class Demo {
public static void main(String[] args) {
System.out.println(MyUtil.max(3, 4));
}
}
class MyUtil {
public static int max(int x, int y) {
return x>y ? x : y;
}
}
代码块
普通代码块
public class Demo {
public static void main(String[] args) {
System.out.println("普通代码块");
{
String name = "张三";
System.out.println(name);
}
{
String name = "张三";
System.out.println(name);
}
System.out.println("普通代码块");
}
}
构造代码块
public class Demo {
public static void main(String[] args) {
new Person();
new Person();
new Person();
}
}
class Person {
public Person() {
System.out.println("实例化对象");
}
{
System.out.println("构造代码块,每次实例化对象前执行");
}
}
静态代码块
public class Demo {
static {
System.out.println("程序初始化");
}
public static void main(String[] args) {
new Person();
new Person();
new Person();
}
}
class Person {
public Person() {
System.out.println("实例化对象");
}
static {
System.out.println("静态代码块");
}
{
System.out.println("构造代码块,每次实例化对象前执行");
}
}
数组
int数组
public class Demo {
public static void main(String[] args) {
int[] arr1 = {2,7,3,9,4};
int[] arr2 = new int[3];
arr2[0] = 11;
arr2[1] = 22;
arr2[2] = 33;
printArr(arr1);
printArr(arr2);
}
public static void printArr(int[] arr) {
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
}
}
foreach
public class Demo {
public static void main(String[] args) {
int[] arr = {2,7,3,9,4};
for (int num : arr) {
System.out.println(num);
}
}
}
多维数组
public class Demo {
public static void main(String[] args) {
int[][] arr = {{1,2,3},{4,5,6},{7,8,9,0}};
for (int[] temp : arr) {
for (int num : temp) {
System.out.print(num + "、");
}
System.out.println();
}
}
}
排序
public class Demo {
public static void main(String[] args) {
int[] arr = { 2, 7, 3, 9, 4 };
// 排序
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 输出
for (int num : arr) {
System.out.print(num + "、");
}
}
}
排序(Java提供的排序方法)
public class Demo {
public static void main(String[] args) {
int[] arr = { 2, 7, 3, 9, 4 };
java.util.Arrays.sort(arr);
String result = java.util.Arrays.toString(arr);
System.out.println(result);
}
}
可变参数
public class Demo {
public static void main(String[] args) {
fun(1);
fun(1,2);
fun(1,2,3);
}
public static void fun(int... arr) {
for(int num : arr) {
System.out.print(num + "、");
}
System.out.println();
}
}
对象数组
public class Demo {
public static void main(String[] args) {
Person[] persons = new Person[2];
persons[0] = new Person("张三", 18);
persons[1] = new Person("李四", 19);
for (Person person : persons) {
System.out.println(person.getInfo());
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getInfo() {
return "姓名:" + name + ", 年龄:" + age;
}
}
类关联结构
public class Demo {
public static void main(String[] args) {
Person person = new Person("张三", 18);
Car car = new Car("宝马", 500000.00);
person.setCar(car);
car.setPerson(person);
System.out.println(person.getCar().getInfo());
System.out.println(car.getPerson().getInfo());
}
}
class Person {
private String name;
private int age;
private Car car;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getInfo() {
return "姓名:" + name + ", 年龄:" + age;
}
}
class Car {
private String name;
private double price;
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Car(String name, double price) {
this.name = name;
this.price = price;
}
public String getInfo() {
return "车名:" + name + ", 价格:" + price;
}
}
字符串
字符串比较
public class Demo {
public static void main(String[] args) {
String str1 = new String("AAA");
String str2 = new String("AAA");
String str3 = "AAA";
System.out.println(str1 == str2);
System.out.println(str2 == str3);
System.out.println(str1.equals(str2));
System.out.println(str2.equals(str3));
}
}
字符串手工入池
public class Demo {
public static void main(String[] args) {
String str1 = "AAA";
String str2 = new String("AAA").intern();
System.out.println(str1 == str2);
}
}
字符串常量池
String s = "a" + "b";
,编译器会进行常量折叠,即变成String s = "ab"
- 对于能够进行优化的
String s = "a" + xxx;
用StringBuilder
的append()
方法替代,最后调用toString()
方法public class Demo {
public static void main(String[] args) {
{
String str1 = "AAA";
String str2 = "AA" + "A";
System.out.println(str1 == str2);
}
{
String str = "A";
String str1 = "AAA";
String str2 = "AA" + str;
System.out.println(str1 == str2);
}
}
}
主方法传参
编译代码:public class Demo {
public static void main(String[] args) {
for (String string : args) {
System.out.println(string);
}
}
}
javac Demo.java
运行程序:java Demo aaa bbb "cccc ddd"
字符串常用方法
```java import java.util.Arrays;
public class Demo { public static void main(String[] args) { String str1 = “hello world”; String str2 = “hello world”; System.out.println(str1.equals(str2));// 是否相等 System.out.println(str1.equalsIgnoreCase(str2));// 是否相等(忽略大小写) System.out.println(str1.compareTo(str2));// 比较大小 System.out.println(str1.compareToIgnoreCase(str2));// 比较大小(忽略大小写) System.out.println(str1.startsWith(“hello”));// 是否以hello开头 System.out.println(str1.endsWith(“hello”));// 是否以hello结尾 System.out.println(str1.contains(“hello”));// 是否包含hello System.out.println(str1.replace(“ “, “-“));// 字符串替换 System.out.println(Arrays.toString(str1.split(“ “)));// 字符串拆分 System.out.println(str1.substring(2, 10));// 字符串截取 System.out.println(str1.substring(6));// 字符串截取 System.out.println(str1.substring(str1.indexOf(“ “)+1));// 字符串截取 System.out.println(String.format(“姓名:%s,年龄:%d,成绩:%5.2f”, “张三”,18,89.123456));// 字符串格式化 System.out.println(str1.charAt(0));// 获取指定位置的字符 System.out.println(str1.isEmpty());// 是否是空字符串 System.out.println(str1.concat(str2));// 字符串拼接 System.out.println(str1.length());// 字符串长度 System.out.println(“ AAA BBB “.trim());// 去除首尾空格 System.out.println(str1.toUpperCase());// 转大写 System.out.println(str1.toCharArray());// 转小写 } }
<a name="IRs3L"></a>
### 数字转字符串
- 第三行和第四行没有任何区别,因为`String.valueOf(i)`也是调用`Integer.toString(i)`来实现的
- 第二行代码其实是`String i1 = (new StringBuilder()).append(i).toString();`,首先创建一个`StringBuilder`对象,然后再调用`append`方法,再调用`toString`方法
int i = 5; String i1 = “” + i; String i2 = String.valueOf(i); String i3 = Integer.toString(i);
<a name="zfbBi"></a>
### String的长度限制
- 字符串有长度限制,在编译期,要求字符串常量池中的常量不能超过65535,并且在javac执行过程中控制了最大值为65534
- 在运行期,长度不能超过Int的范围,否则会抛异常
<a name="EdvDe"></a>
### 字符串拼接的几种方式
常用的字符串拼接方式有五种,分别是使用`+`、使用`concat`、使用`StringBuilder`、使用`StringBuffer`以及使用`StringUtils.join`
- 如果要在一个循环体中进行字符串拼接,直接使用`StringBuilder`的方式是效率最高的
- 如果不是在循环体中进行字符串拼接的话,直接使用`+`就好了
- 如果在并发场景中进行字符串拼接的话,要使用`StringBuffer`来代替`StringBuilder`
<a name="ElvqB"></a>
### JDK 6和JDK 7中substring的原理不同
JDK6:当调用substring方法的时候,会创建一个新的string对象,但是这个string的值仍然指向堆中的同一个字符数组,如果你有一个很长很长的字符串,但是当你使用substring进行切割的时候你只需要很短的一段。这可能导致性能问题,因为你需要的只是一小段字符序列,但是你却引用了整个字符串(因为这个非常长的字符数组一直在被引用,所以无法被回收,就可能导致内存泄露)<br />![](https://cdn.nlark.com/yuque/0/2021/jpeg/12864446/1621326317710-b284c4bf-6862-4b94-9c34-fce3e2adcd77.jpeg#clientId=u82fcec15-6c51-4&from=paste&height=389&id=u91de4ec8&margin=%5Bobject%20Object%5D&originHeight=389&originWidth=650&originalType=url&status=done&style=none&taskId=u626b8c25-f5e3-4927-870e-07851422590&width=650)<br />JDK7:其使用new String创建了一个新字符串,避免对老字符串的引用,从而解决了内存泄露问题<br />![](https://cdn.nlark.com/yuque/0/2021/jpeg/12864446/1621326330128-16543b5c-3fed-46d6-ad29-6ea25f85de08.jpeg#clientId=u82fcec15-6c51-4&from=paste&height=389&id=ua38fd9b0&margin=%5Bobject%20Object%5D&originHeight=389&originWidth=650&originalType=url&status=done&style=none&taskId=u30c373d4-76c8-4415-afdc-a77a5e45f85&width=650)
<a name="RdrjC"></a>
## 继承
<a name="GWHml"></a>
### 继承示例
```java
public class Demo {
public static void main(String[] args) {
Student student = new Student();
student.setName("张三");
student.setAge(18);
student.setSchool("电子科技大学");
System.out.println(student.getSchool());
}
}
// 父类
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
// 子类
class Student extends Person {
private String school;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
方法覆写
public class Demo {
public static void main(String[] args) {
Student student = new Student();
student.setName("张三");
student.setAge(18);
student.setSchool("电子科技大学");
System.out.println(student.info());
}
}
// 父类
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String info() {
return "姓名:" + name + ",年龄:" + age;
}
}
// 子类
class Student extends Person {
private String school;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String info() {
return super.info() + ",学校:" + school;
}
}
重载 VS 重写
- 重载是一个编译期概念、重写是一个运行期间概念
- 重载遵循所谓“编译期绑定”,即在编译时根据参数变量的类型判断应该调用哪个方法
- 重写遵循所谓“运行期绑定”,即在运行的时候,根据引用变量所指向的实际对象的类型来调用方法
因为在编译期已经确定调用哪个方法,所以重载并不是多态。而重写是多态。重载只是一种语言特性,是一种语法规则,与多态无关,与面向对象也无关。(注:严格来说,重载是编译时多态,即静态多态。但是,Java中提到的多态,在不特别说明的情况下都指动态多态)
重写的条件
参数列表必须完全与被重写方法的相同
- 返回类型必须完全与被重写方法的返回类型相同
- 访问级别的限制性一定不能比被重写方法的强
- 访问级别的限制性可以比被重写方法的弱
- 重写方法一定不能抛出新的检查异常或比被重写的方法声明的检查异常更广泛的检查异常
- 重写的方法能够抛出更少或更有限的异常(也就是说,被重写的方法声明了异常,但重写的方法可以什么也不声明)
- 不能重写被标示为final的方法
-
重载的条件
被重载的方法必须改变参数列表
- 被重载的方法可以改变返回类型
- 被重载的方法可以改变访问修饰符
- 被重载的方法可以声明新的或更广的检查异常
-
final
final定义的类不能被继承
- final定义的方法不能被覆盖
- final定义的变量叫常量,值不能改变
注解
@Override(准确覆写)
// 父类
class Person {
public String info() {
return "AAA";
}
}
// 子类
class Student extends Person {
@Override
public String info() {
return "BBB";
}
}
@Deprecated(过时)
```java public class Demo { public static void main(String[] args) {
} } class Person { @Deprecated public String fun() {Person person = new Person();
System.out.println(person.fun());
} }return "AAA";
<a name="WxpM9"></a>
### @SuppressWarnings(压制警告)
```java
public class Demo {
@SuppressWarnings({"deprecation"})
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.fun());
}
}
class Person {
@Deprecated
public String fun() {
return "AAA";
}
}
多态
多态示例
public class Demo {
public static void main(String[] args) {
Message message1 = new Message();
Message message2 = new TextMessage();
Message message3 = new HtmlMessage();
showMsg(message1);
showMsg(message2);
showMsg(message3);
}
public static void showMsg(Message message) {
System.out.println(message.info());
}
}
class Message {
public String info() {
return "Message";
}
}
class TextMessage extends Message {
public String info() {
return "TextMessage";
}
}
class HtmlMessage extends Message {
public String info() {
return "HtmlMessage";
}
}
instanceof
public class Demo {
public static void main(String[] args) {
Message message = new TextMessage();
System.out.println(message.info1());
if(message instanceof TextMessage) {
TextMessage message2 = (TextMessage) message;
System.out.println(message2.info2());
}
}
}
class Message {
public String info1() {
return "Message";
}
}
class TextMessage extends Message {
public String info2() {
return "TextMessage";
}
}
Object
public class Demo {
public static void main(String[] args) {
showMsg(new Message());
}
public static void showMsg(Object obj) {
System.out.println(obj.getClass());
if(obj instanceof Message) {
Message message = (Message) obj;
System.out.println(message.info());
}
}
}
class Message {
public String info() {
return "Message";
}
}
toString
public class Demo {
public static void main(String[] args) {
Person person = new Person();
person.setName("张三");
person.setAge(18);
System.out.println(person);
System.out.println(person.toString());
}
}
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
equals(对象比较)
public class Demo {
public static void main(String[] args) {
Person person1 = new Person("张三", 18);
Person person2 = new Person("张三", 18);
System.out.println(person1.equals(person2));
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
抽象类和抽象方法
public class Demo {
public static void main(String[] args) {
Message message = new TextMessage("MessageMessageMessage");
message.showMsg();
}
}
// 抽象类
abstract class Message {
private String msg;
public Message(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
// 抽象方法
public abstract void showMsg();
}
// 继承抽象类
class TextMessage extends Message {
public TextMessage(String msg) {
super(msg);
}
@Override
public void showMsg() {
System.out.println(getMsg());
}
}
包装类
包装类示例
public class Demo {
public static void main(String[] args) {
Byte byte1 = new Byte((byte) 127);
Short short1 = new Short((short) 1024);
Integer integer = new Integer(18);
Long long1 = new Long(123456789L);
Float float1 = new Float(3.14);
Double double1 = new Double(3.14159);
Boolean boolean1 = new Boolean(true);
Character character = new Character('A');
}
}
定义布尔类型变量的注意事项
success
还是isSuccess
:不要加is
,否则部分框架解析会引起序列化错误boolean
还是Boolean
:局部变量用基本类型,POJO类属性、方法返回值和参数用包装类型boolean success
boolean isSuccess
Boolean success
Boolean isSuccess
自动装箱和自动拆箱
public class Demo {
public static void main(String[] args) {
Integer x = 18;// 自动装箱
int y = x;// 自动拆箱
x++;// 可以计算
System.out.println(x);
System.out.println(y);
// 先自动装箱为Double类型再赋值给obj
Object obj = 3.14159;
if(obj instanceof Double) {
Double double1 = (Double) obj;
System.out.println(double1 + 1.0);
}
// 注意一下
Integer a = 127;
Integer b = 127;
System.out.println(a == b);// true
Integer c = 128;
Integer d = 128;
System.out.println(c == d);// false
System.out.println(c.equals(d));// true
System.out.println(c.intValue() == d.intValue());// true
}
}
接口
接口示例
public class Demo {
public static void main(String[] args) {
Message message = new TextMessage();
System.out.println(message.getMsg());
}
}
interface Message {
String MSG = "MessageMessageMessage";
String getMsg();
}
class TextMessage implements Message {
@Override
public String getMsg() {
return Message.MSG + "AAAAAAA";
}
}
接口多继承和多实现
public class Demo {
public static void main(String[] args) {
Message3 message3 = new TextMessage();
Message4 message4 = new TextMessage();
System.out.println(message3.getMsg1());
System.out.println(message3.getMsg2());
System.out.println(message3.getMsg3());
System.out.println(message4.getMsg4());
}
}
// 简写形式
interface Message1 {
String MSG1 = "MessageMessageMessage";
String getMsg1();
}
// 完整写法
interface Message2 {
public static final String MSG2 = "MessageMessageMessage";
public abstract String getMsg2();
}
// 接口多继承
interface Message3 extends Message1,Message2 {
public abstract String getMsg3();
}
// 接口4
interface Message4 {
public abstract String getMsg4();
}
// 实现类
class TextMessage implements Message3,Message4 {
@Override
public String getMsg1() {
return "111";
}
@Override
public String getMsg2() {
return "222";
}
@Override
public String getMsg3() {
return "333";
}
@Override
public String getMsg4() {
return "444";
}
}
接口增强
public class Demo {
public static void main(String[] args) {
Message message = new TextMessage();
System.out.println(message.getMsg());
System.out.println(message.fun1());
System.out.println(Message.fun2());
}
}
// 增强的接口
interface Message {
public String MSG1 = "MessageMessageMessage";
public String getMsg();
public default String fun1() {
return "BBBBBB";
}
public static String fun2() {
return "CCCCCC";
}
}
// 实现类
class TextMessage implements Message {
@Override
public String getMsg() {
return MSG1 + "AAAAAAAAAA";
}
}
设计模式
工厂设计模式
// 客户端
public class Demo {
public static void main(String[] args) {
Food food = Factory.getInstance(args[0]);
food.eat();
}
}
// 食物接口
interface Food {
public void eat();
}
// 面包实现
class Bread implements Food {
public void eat() {
System.out.println("吃面包");
}
}
// 牛奶实现
class Milk implements Food {
public void eat() {
System.out.println("喝牛奶");
}
}
// 工厂
class Factory {
public static Food getInstance(String type) {
if("bread".equals(type)) {
return new Bread();
}else if("milk".equals(type)) {
return new Milk();
}else {
return null;
}
}
}
编译代码:
javac Demo.java
运行程序:java Demo bread
运行程序:java Demo milk
代理设计模式
// 客户端
public class Demo {
public static void main(String[] args) {
Food food = new FoodProxy(new Bread());
food.eat();
}
}
// 食物接口
interface Food {
public void eat();
}
// 面包实现
class Bread implements Food {
public void eat() {
System.out.println("吃面包");
}
}
// 食物代理
class FoodProxy implements Food {
private Food food;
public FoodProxy(Food food) {
this.food = food;
}
public void eat() {
System.out.println("吃之前处理");
food.eat();
System.out.println("吃之后处理");
}
}
泛型
基本定义
public class Demo {
public static void main(String[] args) {
Message<String> message = new Message<String>("文本消息");
String msg = message.getMsg();
System.out.println(msg);
// 简写形式
Message<Integer> message2 = new Message<>(18);
System.out.println(message2.getMsg());
}
}
// 定义泛型
class Message<T> {
private T msg;
public Message(T msg) {
this.msg = msg;
}
public T getMsg() {
return msg;
}
public void setMsg(T msg) {
this.msg = msg;
}
}
泛型通配符
public class Demo {
public static void main(String[] args) {
Message<Integer> message = new Message<Integer>(18);
Message<Long> message2 = new Message<Long>(123456789L);
printMsg1(message);
printMsg1(message2);
printMsg2(message);
printMsg2(message2);
printMsg3(message);
printMsg3(message2);
}
@SuppressWarnings("rawtypes")
public static void printMsg1(Message message) {
System.out.println(message.getMsg());
}
public static void printMsg2(Message<?> message) {
System.out.println(message.getMsg());
}
// 指定上限
public static void printMsg3(Message<? extends Number> message) {
System.out.println(message.getMsg());
}
// 指定下限
public static void printMsg4(Message<? super String> message) {
System.out.println(message.getMsg());
}
}
class Message<T> {
private T msg;
public Message(T msg) {
this.msg = msg;
}
public T getMsg() {
return msg;
}
public void setMsg(T msg) {
this.msg = msg;
}
}
泛型接口
public class Demo {
public static void main(String[] args) {
Message<Integer> message = new MessageImpl1<Integer>();
System.out.println(message.echo(18));
Message<String> message2 = new MessageImpl2();
System.out.println(message2.echo("AAAA"));
}
}
// 泛型接口
interface Message<T> {
public String echo(T t);
}
// 泛型实现1
class MessageImpl1<T> implements Message<T> {
public String echo(T t) {
return "MessageImpl1" + t;
}
}
//泛型实现2
class MessageImpl2 implements Message<String> {
public String echo(String t) {
return "MessageImpl1" + t;
}
}
泛型方法
```java import java.util.Arrays;
public class Demo { public static void main(String[] args) { Integer[] arr = fun(1,2,3,4,5); System.out.println(Arrays.toString(arr)); }
// 泛型方法
@SuppressWarnings("unchecked")
public static <T> T[] fun(T... args) {
return args;
}
}
<a name="um04k"></a>
## 包
<a name="M9vgj"></a>
### 包的定义
```java
// 定义包
package com.lin1118;
public class Demo {
public static void main(String[] args) {
System.out.println("Hello 世界!");
}
}
编译代码:javac -d . Demo.java
运行程序:java com.lin1118.Demo
导包
package com.lin1118;
public class Message {
public String getMsg() {
return "Message1118";
}
}
package com.lin0216;
public class Message {
public String getMsg() {
return "Message0216";
}
}
package com.lin1234;
public class TextMessage {
public String getMsg() {
return "TextMessage";
}
}
package com.lin1223;
public class HtmlMessage {
public static String getAAA() {
return "AAA";
}
public static String getBBB() {
return "BBB";
}
}
// 导入这个类
import com.lin1118.Message;
// 导入这个包下所有类
import com.lin1234.*;
// 静态导入
import static com.lin1223.HtmlMessage.*;
public class Demo {
public static void main(String[] args) {
// java.lang包下面的类会自动导入比如: java.lang.String
System.out.println(new String("Hello"));
// 这里使用的是: com.lin1118.Message
System.out.println(new Message().getMsg());
// 本Demo程序中有两个Message,所以需要区分一下,下面使用的是: com.lin0216.Message
System.out.println(new com.lin0216.Message().getMsg());
// 下面使用的是: com.lin1234.TextMessage
System.out.println(new TextMessage().getMsg());
// 下面使用的是: com.lin1223.HtmlMessage
System.out.println(getAAA());
System.out.println(getBBB());
}
}
访问控制权限
访问范围 | private | default | protected | public |
---|---|---|---|---|
同一包中的同一类 | √ | √ | √ | √ |
同一包中的不同类 | × | √ | √ | √ |
不同包的子类 | × | × | √ | √ |
不同包的所有类 | × | × | × | √ |
单例
饿汉式
public class Demo {
public static void main(String[] args) {
Massage.getInstance().fun();
}
}
// 单例:饿汉式
class Massage {
private static final Massage MASSAGE = new Massage();
private Massage() {
}
public static Massage getInstance() {
return MASSAGE;
}
public void fun() {
System.out.println("AAA");
}
}
懒汉式
public class Demo {
public static void main(String[] args) {
Massage.getInstance().fun();
}
}
// 单例:懒汉式
class Massage {
private static Massage massage;
private Massage() {
}
public static Massage getInstance() {
if(massage == null) massage = new Massage();
return massage;
}
public void fun() {
System.out.println("AAA");
}
}
枚举
枚举示例
public class Demo {
public static void main(String[] args) {
System.out.println(new Person("张三", 18, Sex.MALE));
System.out.println(new Person("李四", 19, Sex.FEMALE));
// 遍历所有枚举值
for(Sex sex : Sex.values()) {
System.out.println(sex.ordinal() + ":" + sex.name());
}
// 用于switch判断
Sex sex = Sex.MALE;
switch (sex) {
case MALE:
System.out.println("男");
break;
default:
System.out.println("女");
break;
}
}
}
enum Sex {
MALE,FEMALE;
}
class Person {
private String name;
private int age;
private Sex sex;
public Person(String name, int age, Sex sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
枚举结构
public class Demo {
public static void main(String[] args) {
System.out.println(new Person("张三", 18, Sex.MALE));
System.out.println(new Person("李四", 19, Sex.FEMALE));
Message message = Sex.MALE;
System.out.println(message.getMsg());
}
}
// 接口
interface Message {
public String getMsg();
}
// 枚举实现接口
enum Sex implements Message {
// 实例
MALE("男") {
public String fun() {
return title;
}
},FEMALE("女") {
public String fun() {
return title;
}
};
// 属性
protected String title;
// 构造方法
private Sex(String title) {
this.title = title;
}
// toString方法
public String toString() {
return title;
}
// 实现接口的方法
public String getMsg() {
return title;
}
// 每个枚举实例必须实现此方法
public abstract String fun();
}
class Person {
private String name;
private int age;
private Sex sex;
public Person(String name, int age, Sex sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
异常
异常程序
public class Demo {
public static void main(String[] args) {
System.out.println("开始");
System.out.println(10/0);
System.out.println("结束");
}
}
异常处理
public class Demo {
public static void main(String[] args) {
System.out.println("开始");
try {
System.out.println(10/0);
} catch (ArithmeticException e) {
System.out.println("出异常了:" + e);
// 输出异常信息
e.printStackTrace();
}
System.out.println("结束");
}
}
finally
public class Demo {
public static void main(String[] args) {
System.out.println("开始");
try {
System.out.println(10/2);
} catch (ArithmeticException e) {
System.out.println("出异常了:" + e);
// 输出异常信息
e.printStackTrace();
} finally {
System.out.println("出异常 或 不出异常 都会执行");
}
System.out.println("结束");
}
}
public class Demo {
public static void main(String[] args) {
System.out.println("开始");
try {
System.out.println(10/0);
} finally {
System.out.println("出异常 或 不出异常 都会执行");
}
System.out.println("结束");
}
}
多异常处理
public class Demo {
public static void main(String[] args) {
System.out.println("开始");
try {
System.out.println(10 / 0);
System.out.println("AAA".charAt(10));
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束");
}
}
throws
public class Demo {
public static void main(String[] args) {
// 必须处理异常
try {
System.out.println(MyUtil.fun(10, 2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyUtil {
public static int fun(int x, int y) throws Exception {
return x /y;
}
}
public class Demo {
public static void main(String[] args) {
// 可以不处理异常
System.out.println(MyUtil.fun(10, 2));
}
}
class MyUtil {
public static int fun(int x, int y) throws RuntimeException {
return x /y;
}
}
throw
public class Demo {
public static void main(String[] args) {
System.out.println("AAA");
if("aaa".contains("a")) {
throw new RuntimeException("手动抛一个异常");
}
System.out.println("BBB");
}
}
public class Demo {
public static void main(String[] args) {
System.out.println("AAA");
try {
System.out.println(10/0);
} catch (ArithmeticException e) {
throw new RuntimeException("除数不能为0");
}
System.out.println("BBB");
}
}
自定义异常
public class Demo {
public static void main(String[] args) {
System.out.println("AAA");
try {
System.out.println(10/0);
} catch (ArithmeticException e) {
throw new MyException("除数不能为0");
}
System.out.println("BBB");
}
}
// 自定义异常
@SuppressWarnings("serial")
class MyException extends RuntimeException {
public MyException(String message) {
super(message);
}
}
assert(断言)
public class Demo {
public static void main(String[] args) {
int x = 10/2;
assert x==6 : "x的值不是6";
}
}
编译代码:javac Demo.java
运行程序:java -ea Demo
内部类
内部类示例
public class Demo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.fun();
}
}
class Outer {
private String msg = "Hello";
public void fun() {
Inner inner = new Inner();
inner.print();
}
class Inner {
public void print() {
System.out.println(msg);
}
}
}
new内部类
public class Demo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.fun();
Outer.Inner inner = new Outer().new Inner();
inner.print();
}
}
class Outer {
private String msg = "Outer";
public void fun() {
Inner inner = new Inner();
inner.print();
System.out.println(inner.info);
}
class Inner {
private String info = "Inner";
public void print() {
System.out.println(msg);
}
}
}
私有内部类
public class Demo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.fun();
// Inner用private修饰后下面就不能这样使用了
// Outer.Inner inner = new Outer().new Inner();
// inner.print();
}
}
class Outer {
private String msg = "Outer";
public void fun() {
Inner inner = new Inner();
inner.print();
System.out.println(inner.info);
}
private class Inner {
private String info = "Inner";
public void print() {
System.out.println(msg);
}
}
}
内部接口
public class Demo {
public static void main(String[] args) {
Channel channel = new ChannelImpl();
channel.send(((ChannelImpl)channel).new MessageImpl());
}
}
// 有内部接口
interface Channel {
public void send(Message message);
interface Message {
public String getContent();
}
}
// 实现接口
class ChannelImpl implements Channel {
public void send(Message message) {
System.out.println("发送消息:" + message.getContent());
}
// 不实现编译也可以通过
class MessageImpl implements Message {
public String getContent() {
return "Hi Hello";
}
}
}
内部抽象类
public class Demo {
public static void main(String[] args) {
Channel channel = new ChannelImpl();
channel.send(((ChannelImpl)channel).new MessageImpl());
}
}
// 有内部抽象类
interface Channel {
public void send(Message message);
abstract class Message {
public abstract String getContent();
}
}
// 实现接口
class ChannelImpl implements Channel {
public void send(Message message) {
System.out.println("发送消息:" + message.getContent());
}
// 不实现编译也可以通过
class MessageImpl extends Message {
public String getContent() {
return "Hi Hello";
}
}
}
接口内部实现
public class Demo {
public static void main(String[] args) {
Channel channel = Channel.getInstance();
channel.send();
}
}
// 接口内部实现
interface Channel {
public void send();
class ChannelImpl implements Channel {
public void send() {
System.out.println("Hello");
}
}
public static Channel getInstance() {
return new ChannelImpl();
}
}
静态内部类
public class Demo {
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
inner.print();
}
}
class Outer {
private static final String MSG = "Hello";
static class Inner {
public void print() {
System.out.println(MSG);
}
}
}
静态内部接口
public class Demo {
public static void main(String[] args) {
MessageWarp.send(new DefaultMessage(), new NetChannel());
}
}
interface MessageWarp {
static interface Message {
public String getContent();
}
static interface Channel {
public boolean connect();
}
public static void send(Message message, Channel channel) {
if(channel.connect()) {
System.out.println("发送消息:" + message.getContent());
}else {
System.out.println("连接失败");
}
}
}
class DefaultMessage implements MessageWarp.Message {
public String getContent() {
return "Hello";
}
}
class NetChannel implements MessageWarp.Channel {
public boolean connect() {
return true;
}
}
方法里定义内部类
public class Demo {
public static void main(String[] args) {
new Outer().fun(123456);
}
}
class Outer {
private String msg = "Hello";
public void fun(long time) {
final String info = "Info";
class Inner {
public void print() {
System.out.println(msg);
System.out.println(time);
System.out.println(info);
}
}
new Inner().print();
}
}
匿名内部类
public class Demo {
public static void main(String[] args) {
Message message = new MessageImpl();
message.send("Hello");
// 匿名内部类
Message message2 = new Message() {
public void send(String str) {
System.out.println(str);
}
};
message2.send("Hello Hi");
}
}
interface Message {
public void send(String str);
}
class MessageImpl implements Message {
public void send(String str) {
System.out.println(str);
}
}
接口里面匿名内部类
public class Demo {
public static void main(String[] args) {
Message.getInstance().send("Hi");
}
}
interface Message {
public void send(String str);
public static Message getInstance() {
return new Message() {
public void send(String str) {
System.out.println(str);
}
};
}
}
Lambda表达式
public class Demo {
public static void main(String[] args) {
// 匿名内部类写法
Message message = new Message() {
public void send(String str) {
System.out.println(str);
}
};
message.send("Hi");
// Lambda表达式写法
Message message1 = (str) -> {
System.out.println(str);
};
message1.send("Hello");
// 方法没有参数
Message2 message2 = () -> {
System.out.println("AAAAA");
};
message2.send();
// 多个参数
MyMath myMath = (x,y) -> {
System.out.println("------");
return x + y;
};
System.out.println(myMath.add(10, 20));
// 只有一句,省略return
MyMath myMath2 = (x,y) -> x + y;
System.out.println(myMath2.add(10, 20));
}
}
// 函数式接口
@FunctionalInterface
interface Message {
public void send(String str);
}
// 方法没有参数
@FunctionalInterface
interface Message2 {
public void send();
}
// 接口
interface MyMath {
public int add(int x, int y);
}
方法引用
public class Demo {
public static void main(String[] args) {
// 静态方法引用
Function1<Integer,String> fun1 = String :: valueOf;
String str = fun1.change(100);
System.out.println(str.length());
// 实例方法引用
Function2<String> fun2 = "Hello" :: toUpperCase;
System.out.println(fun2.upper());
// 引用指定类中的方法
Function3<String> fun3 = String :: compareTo;
System.out.println(fun3.compare("a", "A"));
// 构造方法的引用
Function4<Person> fun4 = Person :: new;
System.out.println(fun4.create("张三", 18));
}
}
@FunctionalInterface
interface Function1<P,R> {
public R change(P p);
}
@FunctionalInterface
interface Function2<R> {
public R upper();
}
@FunctionalInterface
interface Function3<P> {
public int compare(P p1, P p2);
}
@FunctionalInterface
interface Function4<R> {
public R create(String s, int a);
}
// 类
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
函数式接口
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Demo {
public static void main(String[] args) {
Function<String,Boolean> function = "**Hello" :: startsWith;
System.out.println(function.apply("**"));
Consumer<String> consumer = System.out :: println;
consumer.accept("Hello");
Supplier<String> supplier = "Hello" :: toLowerCase;
System.out.println(supplier.get());
Predicate<String> predicate = "Hello" :: equalsIgnoreCase;
System.out.println(predicate.test("HELLO"));
}
}
Eclipse
下载网址:https://www.eclipse.org/downloads/packages/
下载选择:Eclipse IDE for Enterprise Java and Web Developers