2019.3.13 final与static

final

  • 当使用final修饰类的时候,表示类不能被继承(就是extends后面不能再加它了)

  • final 注意事项:

    • 当使用final修饰时,该方法不能被子类重写

    • 当一个方法被标记为private 那么也会被标记成final,该方法不能被被继承也不能被重写

    • 当final修饰变量或属性时,该变量或属性的值无法被修改(可以叫做常量了)

  • 测试样例

    

    public final class Mosquito {

        public final void fly(){
             
            final int a = 0;    //这个时候a就是0了
                    
            System.out.println("飞");
        }
    }


  • 如果此时我新建一个Wenzi类extand 没有final修饰的Mosquito类,这个fly方法也不能被重写

static

  • static:系统关键字——静态方法

  • 静态方法的特征:

    • 不能直接访问同一个类的属性和非静态方法
    • 可以在main中使用类直接调用方法
    • 静态方法可以访问静态属性或者其他的静态方法
  • 编写静态属性和静态方法样例

  • "Student.java"



    public class Student {

        private String gender;
        private String name;
        private String address;

        private int age;
        
        private static int b;    //这个就是静态变量

        public void sayHi(){

            System.out.println("我叫" + name);
        }
        
        public static void aaa(){    //这个就是静态方法

            System.out.println("bbb ohayou");
        }

        
        public Student() {    //构造方法可以创建空的 方便使用new Student()创建对象
        }

        public Student(String gender, String name, String address, int age) {
            this.gender = gender;
            this.name = name;
            this.address = address;
            this.age = age;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }


  • "MainClass.java"


    public class MainClass {

        public static void main(String[] args) {
    
            Student student = new Student();

            student.setGender("男");
            student.setName("张三");
            student.setAddress("大连市沙河口区");
            student.setAge(14);


            student.aaa();//正常对象调用
            Student.aaa();//静态方法可以直接使用类调用
        }
    }

  • 样例输出
posted @ 2019-03-13 17:23  仲夏今天也在写前端  阅读(207)  评论(0编辑  收藏  举报