首页 > 其他 > 详细

final、static关键字、匿名方法

时间:2019-05-21 20:40:26      阅读:131      评论:0      收藏:0      [点我收藏+]

final
修饰类:不可以被继承 ,但可继承其他类(俗称太监类)

修饰方法:不可以被子类重写,但可以继承使用

修饰局部变量: 一次赋值,终身不变  相当于常量

 

public class Student {
    //final修饰成员变量必须定义就赋值
    final String name="abc";
    final int age;
    public Student (int age){
        this.age=age;
    }
}

 

public class Demo01 {
    public static void main(String[] args) {
        //final修饰的变量:一次赋值,终身不变
        /*final int a;
        a=2;*/
        //final SunZi s=new SunZi()
    }
}

static

static修饰的成员变量属于类,不属于这个类的某个对象.

 

 static修饰的成员可以通过类名直接访问。

定义静态常量

 

 

定义格式:public static final 数据类型 变量 = ;

public class Student {
    private String name;
    private int age;
    public static String schoolname="山东大学";
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
        this.schoolname = schoolname;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    //静态不能访问非静态,非静态可以访问静态
    public static void show(){
        //System.out.println("姓名为"+name+"年龄为"+age);
        System.out.println("学校名称为"+schoolname);
    }
    
}
public class Demo {

    public static void main(String[] args) {
        Student s1=new Student("张三",18);
        Student s2=new Student("李四",18);
        Student s3=new Student("王五",18);
        Student s4=new Student("赵六",18);
        //类名.变量名
        Student.schoolname="北京大学";
        System.out.println(Student.schoolname);
        //类名.方法名
        Student.show();
    }

}

匿名对象

格式:new Person();

 

final、static关键字、匿名方法

原文:https://www.cnblogs.com/boss-H/p/10901858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!