【精选】java进阶——包和final

 博主介绍

‍ 博主介绍:大家好,我是 hacker-routing ,很高兴认识大家~
✨主攻领域:【渗透领域】【应急响应】 【python】 【VulnHub靶场复现】【面试分析】
点赞➕评论➕收藏 == 养成习惯(一键三连)
欢迎关注一起学习一起讨论⭐️一起进步文末有彩蛋
作者水平有限,欢迎各位大佬指点,相互学习进步!


目录

代码

final

常量

代码


  • 包就是文件夹。用来管理各种不同功能的java类,方便后期代码维护。
  • 包名的规则:名称反写+包的作用,需要全部英文小写。

代码

student 类:

package demon9;

public class student {
    private String name;
    private int age;

    public student() {
    }

    public student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }
}

teacher类,但是是别的包里面的

package demon;

public class teacher {
    private String name;
    private int age;

    public teacher() {
    }

    public teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }
}

测试类:test

package demon9;

import demon.teacher;

public class test {
    public static void main(String[] args) {
        //创建对象
//        student s = new student();
//        s.setAge(23);
//        s.setName("张三");
//        System.out.println(s.getName() + "," + s.getAge());

//        String s = "abc";
//        System.out.println(s);

        teacher t = new teacher();


    }
}

final

final修饰方法:
表明该方法是最终方法,不能被重写

final修饰类:
表明该类是最终类,不能被继承

fina1修饰变量:
叫做常量,只能被赋值一次

【精选】java进阶——包和final_第1张图片

package demon1;

public class test {
    public static void main(String[] args) {

    }
    final class fu{
        public final void show(){
            System.out.println("父类的show方法");
        }
    }
//    class zi extends fu{
//
//    }

    
}

常量

  • final修饰的变量是基本类型:那么变量存储的数据值不能发生改变。
  • final修饰的变量是引用类型:那么变量存储的地址值不能发生改变,对象内部的可以改变。

代码

package demon1;


public class test {
    public static void main(String[] args) {

//        - final修饰的变量是基本类型:那么变量存储的数据值不能发生改变。
//        - final修饰的变量是引用类型:那么变量存储的地址值不能发生改变,对象内部的可以改变。

        final double PI = 3.14;

        //创建对象
        final student s = new student("张三",23);
//        变量存储的地址值不能发生改变,对象内部的可以改变
//        s = new student();
        s.setAge(18);
        s.setName("王五");
        System.out.println(s.getName() + "," + s.getAge());

        //数组
        final int[] arr = {1,2,3,4,5};
        arr[0] = 10;
        arr[2] = 30;

        //遍历数组
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

    }


}

你可能感兴趣的:(web,小白学JAVA,java,开发语言,前端,javascript,web安全,final)