1.final修饰:数据、方法和类
1) 修饰属性,表示属性【只能赋值一次】
(1)基本类型:值不能被修改;
(2)引用类型:引用不可以被修改
2) 修饰方法,表示方法不可以重写,但是可以被子类访问(如果方法不是 private 类型话)
3) 修饰类,表示类不可以被继承。
public class FinalDemo {
//final对于基本类型,final使数值恒定不变
//用于对象引用,final使引用恒定不变,
//引用会一直指向此对象,不能改为指向另外一个对象。而对象其自身可以被修改
public final People people = new People(11);
public FinalDemo() {
}
public String getStr(String str) {
final String result = str;
return result;
}
public static void main(String[] args) {
FinalDemo f = new FinalDemo();
System.out.println(f.getStr("1"));
System.out.println(f.getStr("2"));
CC c = new CC();
System.out.println(c.getResult());
//final修饰的方法可以被访问
c.sayHello();
System.out.println(f.people);
//修改引用的i变量
f.people.i += 10;
System.out.println(f.people);
}
}
//final 修饰的类不能被继承
final class Abe {
Abe() {
System.out.println("this is Abe constructor");
}
}
class Bb {
//final修饰的属性,只能赋值一次
final String string = "你好";
//final修饰的方法不能被重写
final void sayHello() {
System.out.println("hello");
}
//private 修饰的方法不能为其他类访问
private final void saybyebye() {
System.out.println("say byebye");
}
void sayHi() {
System.out.println("say hi");
}
String getResult() {
//final修饰的属性,只能赋值一次
// string="他好";
return string;
}
}
class CC extends Bb {
@Override
void sayHi() {
super.sayHi();
}
}
class People {
int i;
public People(int i) {
this.i = i;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Override
public String toString() {
return "People{" +
"i=" + i +
'}';
}
}