thinking in java 学习笔记(三)之重载

简单通过书中的例子,重新温习了一下重载:

package com.halberd.extend;

class Tree {
	int height;

	Tree() {
		System.out.println("Planting a seedling");
		height = 0;
	}

	Tree(int initialHeight) {
		height = initialHeight;
		System.out
				.println("Creating new Tree that is " + height + " feet tall");
	}

	void info() {
		System.out.println("Tree is " + height + " feet tall");
	}

	void info(String s) {
		System.out.println(s + "Tree is " + height + " feet tall");
	}
}

public class OverLoading {
	public static void main(String[] args) {
		new Tree();
		for (int i = 0; i < 5; i++) {
			Tree t = new Tree(i);
			t.info();
			t.info("Overloaded method: ");
		}
	}
}

对于重载的一些基本要求也就那么多,其中值得注意的地方就是在重载的时候不能以参数列表先后顺序不一样来确定重载,这样可以区分两个方法,但是这样会使代码难以维护,却是也没有这个必要,毕竟实现起来没有太大的应用。其次是不能以返回值来区分重载,举了一个最简单明了的例子:

对于方法:

package com.halberd.overload;

public class Overload {
	public static void main(String[] args) {
		
	}
	public void print(){
		System.out.println("void print()");
	}
	public int print(){
		return 2;
		System.out.println("int print()");
	}
}
简单的说如果这样调用int i = print();可能是对的,但是如果就单单这样的调用呢?

print();就让编译器无从下手,所以如上的情况在编译的时候就会报错的。

在构造器重载的时候用this调用重载构造器是很有趣的,不过前提是this调用的时候必须是构造器里面的第一条语句,这里类似于super();但是也就是因为this只能限制到第一条语句,所以每一个构造器最多也只能用一个this来调用另一个构造器:

package com.halberd.constructor;

public class ThisConstructor {
	public static void main(String[] args) {
		new Construtor();
		new Construtor(4);
		new Construtor(3,"6");
	}
}

class Construtor {
	private String name;
	private int id;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Construtor(int id, String name) {
		this(id);
		// this(name);
		// Constructor call must be the first statement in a constructor
		this.name = name;
		System.out.println("int and String");
	}

	public Construtor(int id) {
		this.id = id;
		this.name = "int";
		System.out.println("int");
	}

	public Construtor(String name) {
		this.name = name;
		this.id = 0;
		System.out.println("String");
	}

	public Construtor() {
		System.out.println("null");
	}
}

其实重载说白了就是让人们用起来好用,没有必要把类似的东西分的那么细致,书中对于重载的一个例子是很有魅力的:

你可以说,“清洗衬衣”、“清洗车”、“清洗狗”、但如果硬要这样说的话显得很愚蠢:“以洗衬衣的方式洗衬衣”、“以洗车的方式洗车”、“以洗狗的方式洗狗”。即使漏掉几个词也能理解出其中的意思,不需要对每一个概念都使用不同的词汇--------从具体的语境中就可以推断出含义。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值