zoukankan      html  css  js  c++  java
  • java基础day12---this 关键字-----参数传递

    day12---今天去面试了,更的少

    虽然工资低点,还是毕业的第一份工作,还是挺激动的。

    毕竟最近面了好多家公司了,也累了,应届生不能眼高手低,知道自己几斤几两;但我会慢慢的汲取知识,

    会强大起来!!!!!!
    1.this关键字访问本类中的实例变量
    ---this表示当前这个对象,也就是说当前谁调用这个方法,
    则这个对象是谁
    ---this关键字可以访问本类中的属性
        当局部变量和成员变量没有同名时,则编写属性名等价于this.属性名
            如:id  等价于this.id
        当局部变量和成员变量同名时,并且访问成员变量则必须使用this.
    ---this关键字可以访问本类中的实例方法
        方法名称([参数列表]);等价于 this.方法名称([参数列表])
    ---this关键字访问本类中的其他构造方法
        this();//访问本类无参构造方法;
        this([实参列表]);
        注意:当使用this访问本类构造方法时
        则只能编写在构造方法中,并且是第一条语句

    class Car{
    
    //无参构造
    public Car(){
    
    }
    
    
    //带参构造方法,完成对id和price赋值
    public Car(String id,int price){
    this.id=id;
    this.price=price;
    }
    
    //编写对所有属性赋值的构造方法
    /*public Car(String id,String color,int price){
        this.id=id;
        this.color=color;
        this.price=price;
    }
    */
    
    //编写第二种带参数赋值的构造方法
    public Car(String id,String color,int price){
    //将局部变量id和price的值,给带两个参数的构造方法赋值
    this.(id,price);
    this.color=color;
    
    //this(id,color,price);//构造方法不能出现递归调用,自己调用自己,死循环
    }
    
    //属性
    String id;
    String color;
    int price;
    //方法
    public void print(){
    
    //this();//出现编译错误,必须是构造方法中的第一条语句
    //在本类的方法中,可以直接访问本类中的成员变量(属性)
    //System.out.println("车牌号:"+id+"
    颜色:"+color+"
    价格:"+price);
    //上一条语句,可以编写如下:
    System.out.println("车牌号:"+this.id+"
    颜色:"+this.color+"
    价格:"+this.price);
    }
    }
    class CarTest{
     public static void main(String[] args){
     //实例化车
     Car c=new Car();
     c.print();
     System.out.println(this.id);//出现编译错误,因为this.只能在本类(当前类)中使用
    Car car=new Car();
    car.print();//则print方法中的this.id对象为car,不再是c
    
     //创建对象同时执行带两个参数的构造方法
     Car c4=new Car("京8888",6666666);
     c4.print();
     }
    }


    2.参数传递
    ---基本数据类型作为参数传递
    ---引用数据类型作为参数传递

    3..基本数据类型作为参数传递
    --总结:当基本数据类型作为参数传递时传递的是真正的值,当一个方法中的值发生改变,

      对另一个方法中的值没有任何发生改变,因为两个方法中的变量各自是独立的;

    class Method01{
        public static void change(int x,int y){
            x+=5;
            y+=10;
            System.out.println("x="+x);  //x=15
            System.out.println("y="+y);  //y=30
        }
        public static void main(String[] args){
            int x=10,y=20;
            System.out.println("x="+x);  //x:10
            System.out.println("y="+y);  //y:20
            change(x,y);
            System.out.println("x="+x);  //x的值10
            System.out.println("y="+y);  //y的值20
    
        }
    }
  • 相关阅读:
    HDU 6182 A Math Problem 水题
    HDU 6186 CS Course 位运算 思维
    HDU 6188 Duizi and Shunzi 贪心 思维
    HDU 2824 The Euler function 欧拉函数
    HDU 3037 Saving Beans 多重集合的结合 lucas定理
    HDU 3923 Invoker Polya定理
    FZU 2282 Wand 组合数学 错排公式
    HDU 1452 Happy 2004 数论
    HDU 5778 abs 数论
    欧拉回路【判断连通+度数为偶】
  • 原文地址:https://www.cnblogs.com/fdxjava/p/10651140.html
Copyright © 2011-2022 走看看