static篇
1、被static修饰的成员变量和成员方法独立于该类的任何对象,不需要实例化就可以使用,被类的所有实例共享,在类加载时,根据类名在运行时的数据区中存放
2、static修饰的方法,叫静态方法,修饰的变量,叫静态变量。
static修饰的代码块表示静态代码块,将JVM(java虚拟机)加载时,就会被运行,如图:
public class staticCodes {
static{
System.out.println("这儿是在static修饰的代码块中");
System.out.println("这儿的代码会在加载类时执行");
}
public static void main(String[] args) {
new staticCodes();
}
}
运行结果:
这儿是在static修饰的代码块中
这儿的代码会在加载类时执行
3、成员变量:静态变量、实例变量
静态变量:在内存中只有一个拷贝,仅在类加载时分配内存,推荐使用类名直接访问。
易出错误:忽略不同对象可以更改静态变量
实例变量:创建实例时分配内存,在内存中有多个拷贝,互不影响。对此,可对下面的代码查错,也可忽略~
//这个代码,曾经困扰我好几个小时,人笨,没办法~<img alt="快哭了" src="http://static.blog.youkuaiyun.com/xheditor/xheditor_emot/default/fastcry.gif" />
public class BankRunnableDemo {
//账户类,存储账号金额内容
private static int money;
private static String name;
public BankRunnableDemo(String name,int money) {
this.name = name;
this.money = money;
}
//账户存款取款
public synchronized void getOutMoney(int money){
if(this.money > money){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
this.money -=money;
System.out.print(name +" 取款" + money +"元" + " ");
}
else{
System.out.println("余额不足");
}
}
public synchronized void saveMoney(int money){
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
this.money += money;
System.out.print( name + ": 新存入" + money + "元 ");
}
//存款类
static class SaveMoney implements Runnable{
private BankRunnableDemo account;
private int money;
public SaveMoney(BankRunnableDemo account) {
this.account = account;
}
@Override
public void run() {
account.saveMoney(7);
System.out.println("存钱后余额为:" + account.money);
}
}
//取款类
static class WithDraw implements Runnable{
private BankRunnableDemo account;
public WithDraw(BankRunnableDemo account) {
this.account = account;
}
@Override
public void run() {
account.getOutMoney(8);
System.out.println("取款后余额为:" + account.money);
}
}
public static void main(String[] args) {
//创建存款取款的类
WithDraw t1 = new WithDraw(new BankRunnableDemo("account1",100));
new Thread(t1).start();
WithDraw t2 = new WithDraw(new BankRunnableDemo("account2",500));
new Thread(t2).start();
SaveMoney s1 = new SaveMoney(new BankRunnableDemo("account1",100));
new Thread(s1).start();
SaveMoney s2 = new SaveMoney(new BankRunnableDemo("account2",500));
new Thread(s2).start();
}
}
4静态方法
静态方法可以通过类名或实例调用。
static方法独立于任何实例。不能直接访问非静态成员和非静态方法,及不能访问实例变量和实例方法
final篇
1、final英语翻译是:最后的,最终的;决定性的;不可更改的---->
2、final类不能被继承----->因为抽象类需要被继承实现,所以final不能修饰抽象的类、成员方法、变量
tip1:
ps:private类型的方法默认是final类型的,所以父类的private成员方法不能被子类覆盖。
tip2:
final类不能被继承,所以final类的成员方法没有计划被覆盖,默认都是final,如果一个类不需要改变,不需要子类或扩展,就设计成final类
3、final方法不能被子类的方法覆盖,但可以被继承
使用原因:1、防止继承类的方法修改它 2、高效。编译器在遇到调用final方法时候会转入内嵌机制,大大提高执行效率
4、final不能修饰构造方法
5、final 修饰变量
tip:
因为final变量赋初值后,值将不再改变,并且final定义变量时,可以先声明,而不给初值,这可以使一个类的不同对象拥有值固定不变
static final篇
1、修饰变量时,一旦给值就不可修改,根据之前提到的static内容,该变量通过类名访问
2、修饰方法时,表示给方法不可覆盖,即不可override,通过类名直接访问
本文详细解析了Java中static和final关键字的使用方法及其特性。包括static修饰成员变量、成员方法的特点,静态代码块的执行时机,final修饰类、方法、变量的作用与限制等。
1230

被折叠的 条评论
为什么被折叠?



