美文网首页
final的使用

final的使用

作者: 御都 | 来源:发表于2019-07-26 06:49 被阅读0次
    import java.util.Arrays;
    import org.omg.Messaging.SyncScopeHelper;
    
    class Person{
        int age;
        //在声明时给常量成员属性赋值
        final int[] ss=new int[6];
        final int m =2;
        final int n;
        public static final int PERSON_MAX =180;
        public static final int PERSON_Min;
        //在静态代码块中赋值
        static{
            PERSON_Min=0;
        }
        /*{
            //非static属性能在成员代码块中给常量成员属性赋值
                    n = 3;
        }*/
        public Person(){
            //非static属性也能在构造方法中给常量成员属性赋值
            n = 3;
        }
        public void change1(){
            age =1;
            //The final field Person.m cannot be assigned
            //m = 3;
        }
        //局部变量用final修饰除了不能再赋值,和一般局部变量作用一样
        public void change2(int n,final int m){
            //1 常量可以先声明,再赋值,且一定要赋值
            final int a; 
            a =1;
            n = m;
            System.out.println("n = "+n);
            System.out.println("m = "+m);
            //m =3;//限制了对传入参数m的修改
            }
        //final决定了ds指向的数组内存地址不变,但是元素可变
        public void change3(final int[] ds){
            ds[0] = 66;
        }
        //final
        public void m1(){
            System.out.println("Person.m1()...");
        }
    }
    class CarPerson extends Person{
        //Cannot override the final method from Person
        public void m1(){
            System.out.println("CarPerson.m1()...");
        }
    }
    final class Super{
        
    }
    //final修饰的类不能被继承
    ////The type Sub cannot subclass the final class Super
    //class Sub extends Super{  
    //}
    public class TestFinal {
        public static void main(String[] args) {
            Person p1= new Person();
            p1.ss[0]=2;
            p1.ss[0]=3;
            System.out.println(p1.ss[0]);
            int[] ds = {1,2,3,4,5,6};
            System.out.println(Arrays.toString(ds));
            p1.change3(ds);
            System.out.println(Arrays.toString(ds));
            p1.change2(3, 2);
        }
    }
    

    相关文章

      网友评论

          本文标题:final的使用

          本文链接:https://www.haomeiwen.com/subject/vaplrctx.html