day_05_java_面向对象_四种权限_this_构造器_get/set_import

四种权限:(由低到高)实现高内聚、低耦合

  • prviate :只能在类的内部调用
  • 缺省 :只能在同一个包内调用
  • protected :不同包 但是只要是子类就能调用父类中声明为protected的方法 属性
  • public:只要是同一个工程 就能调用
    在这里插入图片描述
    构造器:constructor
    作用:
  • 创建对象
  • 初始化属性
public class Animal {
    public static void main(String[] args) {

        AnimalLegs p = new AnimalLegs();

对象类型 +名称 = new+构造器
此处AnimalLegs()即为构造器。
若没定义构造器,则系统默认定义空构造器。

    public AnimalLegs(){
        System.out.println("构造器");
    }
    public AnimalLegs(int n){
        System.out.println("重载构造器");
        age = n;
    }

一旦显式定义了构造器,则不在提供默认的空构造器
this关键字:当前对象
在这里插入图片描述
在这里插入图片描述
此时 形参和属性都指向一个位置

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

通过this区分开同名变量
在类的方法中通过” this.属性 “ or”this.方法“调用当前对象的属性
、方法,通常情况省略this,当形参与属性重名时,必须使用this.属性来表明属性而非形参。同理构造器中也可使用this.属性表正在创建的类的属性。
this修饰构造器:this();调用空参构造器。降低构造器冗余;
构造器的互相调用:不能闭环,并且必须放在构造器定义的首行;最多调用一个构造器;

    public  thisTest(){
        System.out.println("1");
    }
    public thisTest(int a){
        this();
        age = a;
        System.out.println(2);
    }
    public  thisTest(int a,String n){
        this(a);
        name = n;
        //age = a; 在this(a);中完成赋值,因此可以省略
        System.out.println(3);
        
    }

import:
在这里插入图片描述
自动生成get、set、构造器方法:

  1. alt + insert
  2. getter and setter (constructor)
  3. Ctrl + 左键选则需要的属性
  4. ok
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值