static & final

static

被static修饰的方法,是类的方法,被static修饰的属性,是类的属性。

static如果放在属性上,

public class Person1 {
    public static String aaa = "中国人";
    
    public String name;
    public int age;

此时aaa是可以直接点出来的,而name,age是需要 Person p = new Person();

p.name才可以出来。 

static放在方法上,如果要直接使用别的方法,别的方法必须有static修饰

public class Digui {
    
    public static void main(String[] args) {
        int s = add(100);
        System.out.println(s);
    }
    public static int add(int i) {
        Digui.main(new String[0]);
        if(i==1) {
            return i;
        } else {
            return i+add(i-1);
        }
    }
}

被static修饰后,直接使用类名就可以点出来。

public class Person1 {
    public static String aaa = "中国人";
    
    public Person1(String name) {
        super();
        this.name = name;
   }
    public static void main(String[] args) {
        Person1 person = new Person1("Dreamlu");
        String xx = Person1.aaa;
    }
}

Final

被final修饰的属性,必须初始化。

初始化有两种:

第一种:

public class Person1 {
    public static final String aaa = "中国人";
    
    public String name;
    public final int age;
    
    public Person1(String name) {
        super();
        this.name = name;
        this.age = 0;
    }

第二种:

public class Person1 {
    public static final String aaa = "中国人";
    
    public String name;
    public final int age=0;
    public Person1(String name) {
        super();
        this.name = name;
    }

被final修饰的类,不能被继承。

被final修饰的方法,不能被重写。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java中static关键字的使用

知识点:java中,static关键字修饰类的变量、方法、代码块、内部类场景:我们在创建类的方法和变量时,如果这个类在创建多个对象时,共用同一个属性或者方法,就可以使用static关键字修饰,因为static修饰的变量,在内存的静态域存在的值,被类的多个实例所共用,实际上我们在编写一个类时,就是在描述对象的属性和行为,并没有产生实质上的对

java中一些常考知识

一、static的作用 static是修饰符,用于修饰成员变量(静态变量/类变量)。static修饰的成员被所有对象共享。static优先于对象存在。static修饰的成员可以用类名.静态成员来访问。注:1.静态方法只能访问静态成员,非静态方法既能访问静态成员又可以访问非静态成员。2.静态方法中不可

Java中static、final、static final的区别

说明:不一定准确,但是最快理解。final:final可以修饰:属性,方法,类,局部变量(方法中的变量)final修饰的属性的初始化可以在编译期,也可以在运行期,初始化后不能被改变。final修饰的属性跟具体对象有关,在运行期初始化的final属性,不同对象可以有不同的值。final修饰的属性表明是一个常数(创建后不能被修改)。