JAVA随笔——关于构造函数与this关键字和static关键字

函数重载:函数重载根据参数不同来进行分别,参数顺序不同也是函数重载,并非同一个函数。例如:

public class OverloadingOrder {
       public static void main(String[] args){
              f(1,"z");
              f("f",2);
       }
       static void f(int i,String s){
              System.out.println(s+i);
       }
       static void f(String s,int i){
              System.out.println(i+s);
       }
}

this关键字
this 主要用于:
      1)需要返回对当前对象的引用时,写在return中
public class Leaf{
	int i=0;
	Leaf increment(){
		i++;
		return this;
	}
	void print(){
		System.out.println("i = "+ i);
	}
	public static void main(String[] args){
		Leaf x=new Leaf();
		x.increment().incremrnt().increment().print();
	}
}/* Output:
i = 3
*/
      2)将当前对象传递给其他方法时

class Person {
  public void eat(Apple apple) {
    Apple peeled = apple.getPeeled();
    System.out.println("Yummy");
  }
}

class Peeler {
  static Apple peel(Apple apple) {
    return apple; // Peeled
  }
}

class Apple {
  Apple getPeeled() { return Peeler.peel(this); }
}

public class PassingThis {
  public static void main(String[] args) {
    new Person().eat(new Apple());
  }
} /* Output:
Yummy
*/

      3)当一个类具有多个构造函数时,可使用this在一个构造函数中调用另一个构造函数,从而避免重复代码。

  Flower(String s, int petals) {
    this(petals);
//!    this(s); // 不能调用两个构造函数
    this.s = s; // Another use of "this"
    print("String & int args");
  }
  Flower() {
    this("hi", 47);
    print("default constructor (no args)");
  }
  void printPetalCount() {
//! this(11); // 不能在非构造函数中调用构造函数
    print("petalCount = " + petalCount + " s = "+ s);
  }
static关键字

1)static方法中没有this,不能在static方法中调用非静态方法,可能调用静态方法和静态域

2)在非静态方法中可以调用静态方法




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值