java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

java里的final和static使用方法

final变量被定义为一个常量,是一个无法修改的量。我们只能给他赋值一次。
final, the variable can be defined as a constant and can not be changed;we only assgin the value for the final variable once.

final定义的方法,无法被重写。
final, the definition of the method can not be covered;

final定义的类,不能被继承
final, the definition of the class can not be inherited.

static.一个分配在内存里的变量。
static, is an area in memory allocated for the entire class of general-purpose, all objects of the class are entitled to the value of its common.

变量可以被修改。我们可以给变量赋值任意次
the variable can be changed. we can assgin a value for the variable any number of times

final static , 我们必须为它赋值。
final static, static preceded by the final.we must assgin a value for the variable.

static and final are not directly related to.

什么时候我们需要使用final
1.when we use final
final.用来保护一个数据,或者方法被重写。
final, used to protect data or methods to be rewritten
1),我们保护一个变量,使他在工程里无法被修改。例如final static double pi = 3.1415926;
1).we protect a variable,make it can not be changed in a project . like { final static double pi = 3.1415926; }
2)保护一个方法被重写
2).we protect a method can not be covered.
3)保护一个类被继承。
3).we protect a method can not be inherited
什么时候使用static
2.when we use static
1)我们需要一个变量,它能被直接在任何对象里使用
1).We need a variable, it can be used directly to any object.
2)我们需要一个方法,它直接被其他对象调用。不需要声明一个新对象。
2).We need a function,it can be used directly to other object,and we do not need to declare a new object.


/**
java-er.com
learn java is so easy
*/

public class Final
{
	final static int a=10;// we must assign a value for 'a'
	static int b;
	int bx = 5;

	public static void main(String[] args){
		//a = 11; //occur a error.  final , assign once

		final int ax; // we do not have to assign a value for 'a1'
		ax = 10;
		// ax = 11; //occur a error.  final , assign once
		
		b = 11;
		b = 12; //ok we can assign it any times.
		System.out.println("a " + a);
		System.out.println("b " + b);
		
		// now, b=12, bx=5
		Final f1 =  new Final();
		f1.b++;
		f1.bx++;
		Final f2 = new Final();
		f2.b++;
		f2.bx++;
		
		System.out.println("f2.b " + f2.b);  // b is changed by f1.b++ and f2.b++
		System.out.println("f2.bx " + f2.bx);// bx is only changed by f2.bx++

	}
}


This entry was posted in JAVA and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-final-static/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply