Java基础复习(六)
常见关键字总结
1、final关键字
final用来修饰类、方法和变量。
(1)final修饰的类不能被继承,而且final修饰的类中,所有成员方法会被默认为final方法,不允被继承重写。
(2)final修饰的方法不能被重写。
(3)final修饰的变量是常量,基本数据类型数值无法改变;引用数据类型。
一般final有两种实现意义:一是将修饰的锁定,使其无法被修改;二是final定义提高效率,早期会将final方法转换为内嵌调用。如今不再需要。
2、static关键字
(1)修饰成员变量和成员方法:所修饰的成员变量和成员方法属于这个类,而不是属于这个类的单个对象,可以被类中所有对象共享。可以通过类来调用,不用创建对象。调用格式:类名.静态变量名 类名.静态方法名()
使用类的静态方法时,注意:
一是在静态方法里只能直接调用同类中其他的静态成员(包括变量和方法),而不能直接访问类中的非静态成员。(因为,如果访问了类中的非静态成员,在调用静态成员时会由于没有创建对象无法调用非静态成员而报错。)
二是静态方法不能引用this和super关键字。(因为静态方法在使用前不用创建任何实例对象,在静态方法调用时,this没有引用对象。)
(2)静态代码块:定义在类内部,类中方法的外部。静态代码块在非静态代码块之前执行(静态代码块 --> 非静态代码块 --> 构造方法),提高运行效率;并且无论创建多少个类的对象,静态代码块只会执行一次。
class Parent{
static String name = "hello";
{
System.out.println("parent block");
}
static {
System.out.println("parent static block");
}
public Parent(){
System.out.println("parent constructor");
}
}
class Child extends Parent{
static String childName = "hello";
{
System.out.println("child block");
}
static {
System.out.println("child static block");
}
public Child(){
System.out.println("child constructor");
}
}
public class Test {
public static void main(String[] args) {
new Child();//语句(*)
}
}
结果:
parent static block
child static block
parent block
parent constructor
child block
child constructor
(3)静态内部类(static修饰类的话只能修饰内部类)
(4)静态导包(导入类中的静态资源,1.5之后新特性):import static 连用指定导入某个类中的指定静态资源,不需要使用类名调用类中静态成员,可以直接使用类中静态成员变量和成员方法。
3、final关键字
final关键字修饰的无法再次改变,可以用来修饰类、方法、成员变量、局部变量。
final修饰的类可以继承其他类,但不可以被继承,即可以有父类但不能有子类;final修饰的方法不可以被重写覆盖;final修饰的变量,只能被唯一赋值一次,不能被重新赋值,修饰的对象不能改变。abstract和final不可以同时使用。
4、this关键字
this用于引用本类中的当前实例,即成员变量、其他成员方法、其他构造方法。
public void setUsername(String username) {
this.username = username;
}
5、super关键字
用于从子类访问父类的变量和方法。
public class Super {
protected int number;
protected showNumber() {
System.out.println("number = " + number);
}
}
public class Sub extends Super {
void bar() {
super.number = 10;
super.showNumber();
}
}
使用 this 和 super 要注意的问题:
在构造器中使用 super()
调用父类中的其他构造方法时,该语句必须处于构造器的首行,否则编译器会报错。另外,this 调用本类中的其他构造方法时,也要放在首行。
this、super不能用在static方法中。
内部类
1、成员内部类:在方法外米娜定义的内部类。内部类调用外部类中的属性或方法,可以直接使用;外部类调用内部类的属性或方法必须现创建对象。
public class Test_inner {
static String str="外部类";
public static class Inner{
String str="内部类";
public void print(){
String str="print方法";
System.out.println(str);
System.out.println(this.str);
System.out.println(Test_inner.str);
}
}
}
public class main {
public static void main(String[] args) {
Test_inner.Inner inner = new Test_inner.Inner();
inner.print();
}
}
结果:
print方法
内部类
外部类
2、局部内部类:在方法内部定义,只能在方法内部调用局部内部类;再调用所在方法内的变量时,该变量必须是不可改变的。
//局部内部类格式:
public void methodOuter(){
class Inner{
String str="局部内部类";
public void print(){
System.out.println(str);
}
}
}
//匿名内部类格式(省略类名):
Inner inner = new Inner(){
public void print(){
System.out.println("匿名内部类");
}
}