ToB企服应用市场:ToB评测及商务社交产业平台
标题:
Static、Final关键字详解
[打印本页]
作者:
锦通
时间:
2022-8-25 08:10
标题:
Static、Final关键字详解
1.Static
详情见下面代码讲解点击查看代码
package com.Tang.oop.demo07;
public class Student {
private static int age;//静态变量
private double score;//非静态变量
public void run(){
go();//非静态方法可以调用静态方法
}
public static void go(){
}
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age);//静态变量可以被类中的所有实例去共享
//System.out.println(Student.score);这个就会报错,非静态变量并不能用类名去访问
System.out.println(s1.score);
System.out.println(s1.age);
//run();//在静态方法中不能直接调用非静态方法
new Student().run();//必须得通过new一个对象来调用
}
}
复制代码
2.代码块(静态,匿名,构造)
点击查看代码
package com.Tang.oop.demo07;
public class Person {
{//这一部分就是匿名代码块
System.out.println("匿名代码块");
}
static{//这一部分就是静态代码块,且只执行一次
System.out.println("静态代码块");
}
public Person() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person = new Person();
System.out.println("=============");
Person person1 = new Person();
}
}
复制代码
运行结果
3.final
final为常量,被其修饰的类就无法被继承,也就是不能有子类当父类Person被final修饰时,子类Student就无法在继承Person如下图
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4