Object类

1. Object类

  1. object类是java中的一个特殊的类,Java中的所有类都直接或间接继承了Object 类
  2. 当定义了一个新类时,如果没有用extends确定这个类继承了某类,那么则默认继承 Object类

2. equals与 “==”

	String s1 = "ABC";
	String s2 = "ABC";
	String s3 = new String("ABC");
	String s4 = new String("ABCD");
	//==只能比较变量是否相等
	System.out.println(s1 == s2);//T
	System.out.println(s1 == s3);//F
	//只要对象的内容一样,就可以使用equals比较得到
	//相等(equals)的结果
	System.out.println(s1.equals(s2));//T
	System.out.println(s1.equals(s3));//T
	System.out.println(s1.equals(s4));//F		

3. 使用equals比较对象相等

  1. 案例1:
	Scanner sc = new Scanner(System.in);
	System.out.print("用户名");
	String name = sc.nextLine();
	System.out.print("密码");
	String pwd = sc.nextLine();
	
	
	//判定是否是“熊大”,“123”
	if (name == "熊大" && pwd == "123") {
		System.out.println("成功");
	} else {
		System.out.println("失败");
	}
	
	if (name.equals("熊大") && pwd.equals("123")) {
		System.out.println("成功");
	} else {
		System.out.println("失败");
	}
  1. 案例2:
	public static void main(String[] args) {
		/**
		 * 比较两个Cell是否相等
		 */
		Cell c1 = new Cell(0, 3);
		Cell c2 = new Cell(0, 3);
		Cell c3 = new Cell(0, 6);
		//使用==比较,只能比较引用值
		System.out.println(c1 == c2);//F
		System.out.println(c1 == c3);//F
		/**
		 * 使用equals比较,Object提供的默认equals方法,利用==比较的,并不理想
		 * Java建议子类重写equals方法,抽象为根据对象的关键属性比较两个对象是否相等
		 */
		System.out.println(c1.equals(c2));//F
		System.out.println(c1.equals(c3));//F				
	}
	class Cell{
		int row;
		int col;
		public Cell(int row, int col) {
			super();
			this.row = row;
			this.col = col;
		}
	
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + col;
			result = prime * result + row;
			return result;
		}
	
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Cell other = (Cell) obj;
			if (col != other.col)
				return false;
			if (row != other.row)
				return false;
			return true;
		}
		@Override
		public String toString() {
			return "Cell [row=" + row + ", col=" + col + "]";
		}	
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值