zoukankan      html  css  js  c++  java
  • this、访问修饰符——Java笔记(五)

    this
            表示当前对象
            谁调用方法谁就是当前对象
    用static修饰的代码块里面不能使用this
    方法里面有一个和字段同名的局部变量时,不能省略this
     
    this还可以用于构造器里面调用构造器:
            this(参数...);
    例:
     1 public class Dog {
     2  //颜色
     3  String color;
     4  //名称
     5  String name;
     6  //体重
     7  int weight;
     8  
     9  public Dog(){}
    10  public Dog(String color,String name,int weight){
    11   this.color = color;
    12   this.name = name;
    13   this.weight = weight;
    14  }
    15  
    16  public String getColor(){
    17   return color;
    18  }
    19  public void setColor(String color){
    20   this.color = color;
    21  }
    22  
    23  public static void main(String[] args) {
    24  
    25   Dog dog = new Dog();
    26   dog.setColor("red");
    27  
    28   System.out.println( dog.getColor()); //red
    29  }
    30 }
     
    dog.setColor("red");
    这行代码dog调用了setColor()方法,即里面那个this指向的就是当前调用的那个对象即dog;
     
    若setColor()方法没有使用this而是color = color,那么利用getColor()获取到的则是空,因为他们字段名相同,都是把自己赋值给自己。
    当在类里面增加这两个构造器时:
        public Dog(String color){
              this.color = color;
     }
     public Dog(String color,String name){
      this.color = color;
      this.name = name;
     }
    我们可以使用构造器里面调用构造器即
        this(name);
    那么
          public Dog(String color,String name){
      this.color = color;
    //  this.name = name;
    this(name);
     }
    还可以this(color,name);
    public Dog(String color,String name,int weight){
    //  this.color = color;
      //this.name = name;
    //这两行代码可以使用这一句来代替   
       this(color,name);
      this.weight = weight;
     }
     
    访问修饰符:
        public(公共的): 公共访问权限,任何地方你都能访问,能继承子类
        private(私有的):私有的访问权限也叫类访问权限,只能在本类内部可以访问,不能继承到之类
        default(包访问):包访问权限,什么修饰符都不写就是默认的包访问权限,奔雷内部可以访问,同包的其他类可以访问,同包可以继承
        protected(受保护):受保护的访问权限也叫子类访问权限,本类内部可以访问,不同包的子类可以访问,同包的其他类可以访问,能继承到子类
    修饰符
    类内部
    同一个包
    子类
    任何地方
    public
    protected
     
    default
     
     
    private
     
     
     
     
     
     
  • 相关阅读:
    HDU 1221 Rectangle and Circle 考虑很多情况,good题
    HDU 1223 打表 + 大数
    17984 FFF团的怒火
    17978 倒不了的塔 注意题目
    .. HDU
    17972 Golden gun的巧克力
    9718 整数因子分解(必做) 分治法
    51NOD 1201 整数划分
    Amazon Rekognition 人脸识别
    AWS Config
  • 原文地址:https://www.cnblogs.com/Essence/p/3963352.html
Copyright © 2011-2022 走看看