一.包(package)
- 包:其实就是文件夹
- 作用:对类进行分类管理
- 包定义格式:package 包名(多级包名用. 分开)
- 导入包:使用不同包下类时,需要写类的全路径为简化,就使用import
- 导包格式:import 包名;如:import com.Demo.a1;或import com.Demo.*;
- 如果在同一包下则不需要导包import
二.状态修饰符
一.final(最终态)
- final关键字词的含义: 最终的, 用它修饰之后表示不能再改变了
- final能修饰的内容: 修饰类, 修饰方法, 变量
- 修饰类:
- 表示一个类是最终的类, 表示这个类不能有子类 (不能被其他的类继承)
- 一个类如果被final修饰,这个类中所有的方法都不能被重写
- 修饰方法:
一个方法如果被final修饰了,这个方法不能被重写
- 修饰变量:
- 一个变量如果被final修饰之后,就会变成常量,不能再次赋值,只能赋值一次
- 可以定义和赋值同时进行; 如:final int a = 10
- 定义和赋值分离, 但是也只能赋值一次; final int b; b = 10
- 使用final定义的变量称之为:常量 常量名要是用纯大写的字母多个单词之间使用下划线连接: final int MAX_VAULE = 10; final int MIN = 1
- 修饰局部变量:
- final修饰的变量是基本类型的数据值不会改变
- final修饰的变量为引用类型则地址值不会发生改变,但地址里面的内容可以发发生改变
- 代码案例:
public class Student {
public int age = 21;
}
public class finalDemo {
public static void main(String[] args) {
final int age = 30;
System.out.println(age);
final Student s = new Student();
s.age = 200;
System.out.println(s);
s.age = 300;
System.out.println(s);
System.out.println(s.age);
}
}
二.static(静态)
- static关键字含义:静态;可以修饰成员方法成员变量,成员方法
- static修饰特点:被类的所有对象共享访问
- 代码案例:
public class Student {
public int age;
public String name;
public static String university;
public void show() {
System.out.println(age + "," + name + "," + university);
}
}
public class StaticDemo {
public static void main(String[] args) {
Student.university="qinghua";
Student s = new Student();
s.age = 20;
s.name = "xiaojiang";
s.show();
Student s2 = new Student();
s2.age = 21;
s2.name = "xiaoning";
s2.show();
Student s3 = new Student();
s3.age = 22;
s3.name = "xiaoyun";
s3.show();
}
}
- static访问特点:总之静态成员方法只能访问静态成员
- 非静态成员方法:
- 能够访问静态的成员变量
- 能够访问非静态的成员变量
- 能够访问静态的成员方法
- 能够访问非静态的成员方法
- 静态的成员方法:
- 能够访问成员变量,但不能直接访问
- 能够访问成员方法,但不能直接访问
- 代码案例:
public class Student2 {
public String name = "xiaojiang";
public static String university = "beida";
public void show1() {
System.out.println(name);
System.out.println(university);
show2();
show3();
}
public void show2() {
}
public static void show3() {
System.out.println(university);
show3();
show4();
}
public static void show4() {
}
}
- 静态应用:
public class Student {
public int age;
public static String name;
public void show1() {
System.out.println("非静态show1成员方法");
}
public static void show2() {
System.out.println("静态show2成员方法");
}
}
public class Demo {
public static void main(String[] args) {
Student s = new Student();
s.show1();
s.age = 20;
System.out.println(s.age);
Student.show2();
Student.name = "xiaojiang";
System.out.println(Student.name);
}
}
- static应用场景Java中常量Constant:
public class Constant {
public final static int CODE_10 = 10;
public final static int CODE_20 = 20;
public final static int CODE_30 = 30;
}
public class ConstantDemo {
public static void main(String[] args) {
int code = 10;
if (Constant.CODE_10 == code) {
System.out.println("成功");
return;
}
if (Constant.CODE_20 == code) {
System.out.println("错误");
return;
}
if (Constant.CODE_30 == code) {
System.out.println("找不到");
return;
}
}
}