1. static
关键字
static
:静态的,意为全局的,由该关键字标记的变量或者方法由整个类所共享。- 没有对象的实例,可以使用
类名.方法名()
的形式访问由static
修饰的类方法。 - 在
static
方法内部,只能访问类的static
属性,不能访问非static
属性。 - 因为不需要实例就可以访问
static
方法,因此,static
方法内部也不能有this
和super
。
public class Account {
private final int id;
private final int balance;
private final String password;
private static double interestRate;
private static int minBalance;
private static int initId = 1000;
public Account(int balance, String password) {
id = initId++;
this.balance = balance;
this.password = password;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", balance=" + balance +
", password='" + password + '\'' +
'}';
}
}
public class TestBalance {
public static void main(String[] args) {
Account account = new Account(1000, "12345");
System.out.println(account);
Account account1 = new Account(2000, "fewrd");
System.out.println(account1);
}
}
2. 静态初始化
一个类中可以使用不包含在任何方法体中的静态代码块。当类被载入时,静态代码块被执行,且只被执行一次,静态代码块经常用来进行类属性的初始化。
public class TestStatic {
static String name;
int age;
static {
System.out.println("静态代码块。。。。。");
}
{
age = 10;
System.out.println("非静态代码块。。。");
}
public TestStatic(){
System.out.println("构造器。。。。。。");
}
static void test(){
System.out.println(name + "在测试中。。");
}
void method(){
System.out.println(name + "在跑步,年龄是:" + this.age);
}
public static void main(String[] args) {
TestStatic.name ="Tom";
TestStatic.test();
TestStatic testStatic = new TestStatic();
name = "Jess";
testStatic.age = 12;
testStatic.method();
System.out.println(name);
TestStatic testStatic1 = new TestStatic();
TestStatic.name = "Lucy";
testStatic1.method();
System.out.println(TestStatic.name);
}
}
3. 单子模式
在类的外部不能通过new
构造器的方法创建实例。
public class SingleTon {
private static SingleTon onlyone = new SingleTon();
private String name;
public static SingleTon getString(){
return onlyone;
}
private SingleTon(){
}
}
public class TestSingle{
public static void main(String[] args) {
SingleTon singleTon1 = SingleTon.getString();
SingleTon singleTon2 = SingleTon.getString();
if(singleTon1 == singleTon2)
System.out.println("s1 == s2");
}
}
4. final
关键字
-
使用final
标记的变量即成为了常量,只能赋值一次。
-
final
标记的类不能被继承,提高安全性,提高可读性。
-
final
标记的方法不能被子类所重写,增加安全性。
-
final
标记的成员变量,必须在声明的同时,或在每个构造器中显示赋值,然后才能使用。
final
关键字 表示最终的 可以修饰类 属性 和 方法 表示最终的。final
修饰属性 是最终的属性 属性值不能被修改 是最终的属性。final
修饰的方法 是最终的方法 该方法不能被 修改 该方法不能被重写。final
修饰的类 是最终的类 该类不能被扩展 该类不能被继承。
public class Test {
final int value;
public Test(int value) {
this.value = value;
}
public static void main(String[] args) {
Test test = new Test(2);
Test test1 = new Test(3);
}
}
public class Animal {
public final void run(){
System.out.println("动物会走。。。");
}
}
5. abstract
关键字
用abstract
来修饰一个类时,这个类是抽象类;用abstract
来修饰一个方法时,这个方法叫抽象方法。
抽象方法:只有方法的声明,没有方法的实现。
含有抽象方法的类必声明为抽象类,抽象类不能被实例化,抽象类是用来继承的,抽象类的子类必须重写该抽象类,并提供方法体。
不能用abstract
方法来修饰私有方法,构造方法,静态方法。
一个类不能同时被final
和abstract
修饰。
public abstract class SuperClass{
abstract void m();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)