Java 面向对象(中)2 —— Object类、包装类

目录

1 Object类

1.1 面试题: == 和 equals() 区别

1.1.1 重写equals()代码

1.2 Object类的使用 练习题

1.3 mini Project(重写equals)

1.4 ToString 类

1.4.1 mini Project 综合考察:重写 equals和toString

2 包装类

2.1 单元测试

2.2 包装类的使用

2.3 基本数据类型和包装类如何相互转换

2.3.1 基本数据类型 --->包装类:调用包装类的构造器 

2.3.2 包装类--->基本数据类型:调用包装类Xxx的xxxValue()

2.3.3 常用!自动拆箱装箱:基本数据类型 <——> 包装类

2.3.4 常用!基本数据类型、包装类--->String类型:调用String重载的valueOf(Xxx xxx)

2.3.5 常用!String类型 --->基本数据类型、包装类:调用包装类的parseXxx(String s)

2.4 面试题

2.5 mini Project 


1 Object类

1.1 面试题: == 和 equals() 区别

/*
 * 一、回顾 == 的使用:
 * == :运算符
 * 1. 可以使用在基本数据类型变量和引用数据类型变量中 —— 两种变量都适用
 * 2. 如果比较的是基本数据类型变量:比较两个变量保存的数据是否相等。(不一定类型要相同)
 *    如果比较的是引用数据类型变量:比较两个对象的地址值是否相同.即两个引用是否指向同一个对象实体
 * 补充: == 符号使用时,必须保证符号左右两边的变量类型一致。


 * 二、equals()方法的使用:
 * 1. 是一个方法,而非运算符
 * 2. 只能适用于引用数据类型
 * 3. Object类中equals()的定义:
 *    public boolean equals(Object obj) {
            return (this == obj);
      }
 *    说明:Object类中定义的equals()和==的作用是相同的:比较两个对象的地址值是否相同.即两个引用是否指向同一个对象实体
 
 * 4. 像String、Date、File、包装类等都重写了Object类中的equals()方法。重写以后,比较的不是
 *    两个引用的地址是否相同,而是比较两个对象的"实体内容"是否相同。
  *    对于自定义的类型也要重写equals()方法——否则用的还是Object里面的


 * 5. 通常情况下,我们自定义的类如果使用equals()的话,也通常是比较两个对象的"实体内容"是否相同。那么,我们
 *    就需要对Object类中的equals()进行重写.
 *    重写的原则:比较两个对象的实体内容是否相同.

package com.lee.java1;

public class EqualsTest {
	public static void main(String[] args) {
		int i = 10;
		int j = 10;
		double d = 10.0;
		
		System.out.println(i == j);
		System.out.println(i == d);//int > double
		
		char c = 10;
		System.out.println(i == c);//true
		
		//不能和boolean一起玩
		boolean b = true;
		//System.out.println(i == b);
		
		//引用类型
		Customer cust1 = new Customer("Tom", 21);
		Customer cust2 = new Customer("Tom", 21);
		System.out.println(cust1 == cust2);//false 地址值不一样
		
		String str1 = new String("atguigu");
		String str2 = new String("atguigu");
		System.out.println(str1 == str2);//false
		
		System.out.println("**************************************");
		System.out.println(cust1.equals(cust2));//false--->true
		System.out.println(str1.equals(str2));//true String 重写过
	}
}


 */

参考 String equals() 重写 Customer equals()

1.1.1 重写equals()代码

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj instanceof Customer) {
			Customer cust = (Customer)obj;
			//比较两个对象的每个属性是否都相同
			if (this.age == cust.age && this.name.equals(cust.name)) {
				return true;
			}
		}
		return false;
	}

1.2 Object类的使用 练习题

1.3 mini Project(重写equals)

package com.lee.exer2;

public class OrderTest {
	public static void main(String[] args) {
		Order order1 = new Order(1001, "AA");
		Order order2 = new Order(1001, new String("BB"));
		
		System.out.println(order1.equals(order2));
		
		Order order3 = new Order(1001, "BB");
		System.out.println(order2.equals(order3));
		
		//String的内容在常量池。
		//常量池如果定义了两个值一样的变量,则新的指针指向原先的对象
//		String s1 = "BB";
//		String s2 = "BB";
//		System.out.println(s1 == s2);//true
		
	}
}

class Order {
	private int orderId;
	private String orderName;
	
	public int getOrderId() {
		return orderId;
	}
	public void setOrderId(int orderId) {
		this.orderId = orderId;
	}
	public String getOrderName() {
		return orderName;
	}
	public void setOrderName(String orderName) {
		this.orderName = orderName;
	}
	public Order(int orderId, String orderName) {
		super();
		this.orderId = orderId;
		this.orderName = orderName;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		
		if (obj instanceof Order) {
			//强转 调用order的属性
			Order order = (Order)obj;
			return this.orderId == order.orderId && 
					this.orderName.equals(order.orderName);
		}
		return false;
	}
	
}

1.4 ToString 类

/*
 * Object类中toString()的使用:
 * 
 * 1. 当我们输出一个对象的引用时,实际上就是调用当前对象的toString()
 * 
 * 2. Object类中toString()的定义:
 *   public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
     }
 * 
 * 3. 像String、Date、File、包装类等都重写了Object类中的toString()方法。
 *    使得在调用对象的toString()时,返回"实体内容"信息
 *    
 * 4. 自定义类也可以重写toString()方法,当调用此方法时,返回对象的"实体内容"
 */

package com.lee.java1;

import java.sql.Date;

public class ToString {
	public static void main(String[] args) {
		Customer cust1 = new Customer("Tom", 21);
		System.out.println(cust1.toString());//com.lee.java1.Customer@15db9742
		System.out.println(cust1);//com.lee.java1.Customer@15db9742
		
		String str = new String("MM");
		System.out.println(str);
		
		Date date = new Date(41442414421L);
		System.out.println(date.toString());
	}
	
}

1.4.1 mini Project 综合考察:重写 equals和toString

快捷键:shift + alt + s 

  1. 利用快捷键生成get / set这不是考察的重点
  2. 单参构造器如何利用了父类的空参构造器?
  3. 三参构造器如何传递参数给父类的双参构造器?
  4. 重写equals时的逻辑很重要
  5. 利用快捷键重写tuString
//父类
package com.lee.exer3;

public class GeometricObject {
	protected String color;
	protected double weight;
	
	protected GeometricObject() {
		super();
		this.color = "white";
		this.weight = 1.0;
		
	}
	protected GeometricObject(String color, double weight) {
		super();
		this.color = color;
		this.weight = weight;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
}

//子类
//争取独立写出我注释的内容 


package com.lee.exer3;

public class Circle extends GeometricObject {
	private double radius;

//	public Circle() {
//		super();
//		radius = 1.0;
		color = "white";
		weight = 1.0;
//	}
//
//	public Circle(double radius) {
//		super();
//		this.radius = radius;
//	}
//	
//	public Circle(double radius,String color,double weight) {
//		super(color,weight);
//		this.radius = radius;
//	}

	public double getRadius() {
		return radius;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}
	//求圆的面积
	public double findArea(){
		return 3.14 * radius * radius;
	}
	//比较两个圆的半径是否相等,如相等,返回true。
	@Override
//	public boolean equals(Object obj) {
//		
//		if(this == obj){
//			return true;
//		}
//		
//		if(obj instanceof Circle){
//			Circle c = (Circle)obj;
//			return this.radius == c.radius;
//		}
//		
//		return false;
//		
//	}

	@Override
	public String toString() {
		return "Circle [radius=" + radius + "]";
	}
}

//测试类

package com.lee.exer3;

public class CircleTest {
	public static void main(String[] args) {
		Circle circle1 = new Circle(2.3);
		Circle circle2 = new Circle(3.3, new String("white"), 2.0);
		
		System.out.println("颜色是否相等:" + circle1.getColor().equals(circle2.getColor()));
		
		System.out.println("半径是否相等:" + circle1.equals(circle2));
		
		System.out.println(circle1);
		System.out.println(circle2.toString());
	}
}

2 包装类

2.1 单元测试

/*
 * Java中的JUnit单元测试
 * 
 * 步骤:
 * 1.选中当前工程day13 - 右键选择:build path - add libraries - JUnit 4 - 下一步


 * 2.创建Java类,进行单元测试。
 *   此时的Java类要求:① 此类是public的  ②此类提供公共的无参的构造器


 * 3.此类中声明单元测试方法。
 *   此时的单元测试方法:方法的权限是public, 没有返回值,没有形参

    @Test
    public void testEquals() {
        
    }
 * 4.此单元测试方法上需要声明注解:@Test,并在单元测试类中导入:import org.junit.Test;
 * 
 * 5.声明好单元测试方法以后,就可以在方法体内测试相关的代码。
 * 6.写完代码以后,左键双击单元测试方法名,右键:run as - JUnit Test
 * 
 * 说明:
 * 1.如果执行结果没有任何异常:绿条
 * 2.如果执行结果出现异常:红条
 */

package com.lee.java2;

import org.junit.Test;

public class JUnitTest {
	int num = 10;
	
	@Test
	public void testEquals() {
		String s1 = "MM";
		String s2 = "MM";
		System.out.println(s1.equals(s2));
		
//		Object obj = new String("GG");
//		Date date = (Date)obj;
		
		System.out.println(num);
	}
}

2.2 包装类的使用

把基本数据类型封装到一个类里面,使得其也具有类的功能

2.3 基本数据类型和包装类如何相互转换

/*
 * 包装类的使用:
 * 1.java提供了8种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征
 *  * 2.掌握的:基本数据类型、包装类、String三者之间的相互转换
 */

2.3.1 基本数据类型 --->包装类:调用包装类的构造器 

//基本数据类型 --->包装类:调用包装类的构造器
//单元测试
	@Test
	public void Test1() {
		 
		 //把10包装起来
		 int num1 = 10;
		 Integer in1 = new Integer(num1);
		 System.out.println(in1.toString());
		 
		 
		 Integer in2 = new Integer("123");
		 System.out.println(in2.toString());
		 
		 //参数必须是纯粹的一个数
//		 Integer in3 = new Integer("123a");
//		 System.out.println(in3.toString());
		 
		 Float f1 = new Float(12.3f);
		 Float f2 = new Float("12.3");
		 System.out.println(f1);
		 System.out.println(f2);
		 
		 Boolean b1 = new Boolean(true);
		 Boolean b2 = new Boolean("TrUe");
		 System.out.println(b2);//true
		 Boolean b3 = new Boolean("1true");
		 System.out.println(b3);//false
		 
		 Order order = new Order();
		 System.out.println(order.isMale);
		 System.out.println(order.isFemale);//null
	 }

//类
class Order{
	boolean isMale;
	Boolean isFemale;//一个类
}

2.3.2 包装类--->基本数据类型:调用包装类Xxx的xxxValue()

	@Test public void test2() {
		Integer in1 = new Integer(12);
		int i1 = in1.intValue();
		System.out.println(i1 + 10);	
		
		Float f1 = new Float(123.33f);
		System.out.println(f1.floatValue() + 10);
	}

2.3.3 常用!自动拆箱装箱:基本数据类型 <——> 包装类

//基本数据类型 --> 包装类的对象
	//目的:以多态的方式放入方法
	public void test0() {
		int num1 = 10;
		method(num1);
		
		//自动装箱:类 = int
		int num2 = 10;
		Integer in1 = num2;
		
		boolean b1 = true;
		Boolean b2 = b1;//自动装箱
		
		//自动拆箱:包装类--->基本数据类型
		System.out.println(in1.toString());
		
		int num3 = in1;//自动拆箱
	}

2.3.4 常用!基本数据类型、包装类--->String类型:调用String重载的valueOf(Xxx xxx)

	@Test
	public void test4(){
		int num1 = 10;
		//方式1:连接运算
		String str1 = num1 + "";
		
		//方式2:调用String的valueOf(Xxx xxx)
		float f1 = 12.3f;
		String str2 = String.valueOf(f1);//"12.3"
		
		Double d1 = new Double(12.4);
		String str3 = String.valueOf(d1);
		
		System.out.println(str2);
		System.out.println(str3);
	}

2.3.5 常用!String类型 --->基本数据类型、包装类:调用包装类的parseXxx(String s)

	@Test
	public void test5(){
		String str1 = "123";
		//错误的情况:
//		int num1 = (int)str1;
//		Integer in1 = (Integer)str1;
		
		//可能会报NumberFormatException
		int num2 = Integer.parseInt(str1);
		System.out.println(num2 + 1);
		
		String str2 = "true1";
		boolean b1 = Boolean.parseBoolean(str2);
		System.out.println(b1);
	}

2.4 面试题

	@Test
	public void test0() {
		Object o;
		System.out.println(o = true);
	}
	@Test
	public void test1() {
		//new Integer(1) : new Double(2.0) 编译时两者类型必须提升至同一个
		Object o1 = true ? new Integer(1) : new Double(2.0);
		System.out.println(o1);// 1.0

	}

	@Test
	public void test2() {
		Object o2;
		if (true)
			o2 = new Integer(1);
		else
			o2 = new Double(2.0);
		System.out.println(o2);// 1

	}
	@Test
	public void test3() {
		Integer i = new Integer(1);
		Integer j = new Integer(1);
		System.out.println(i == j);//false
		
		//Integer内部定义了IntegerCache结构,IntegerCache中定义了Integer[],
		//保存了从-128~127范围的整数。如果我们使用自动装箱的方式,给Integer赋值的范围在
		//-128~127范围内时,可以直接使用数组中的元素,不用再去new了。目的:提高效率
		
		Integer m = 1;
		Integer n = 1;
		System.out.println(m == n);//true

		Integer x = 128;//相当于new了一个Integer对象
		Integer y = 128;//相当于new了一个Integer对象
		System.out.println(x == y);//false
	}

2.5 mini Project 

package com.lee.exer4;

import java.util.Scanner;
import java.util.Vector;

public class ScoreTest {
	public static void main(String[] args) {
		//1.实例化Scanner,用于从键盘获取学生成绩
		Scanner scan = new Scanner(System.in);
		
		//2.创建Vector对象:Vector v=new Vector();相当于原来的数组
		Vector v = new Vector();
		
		//3.通过for(;;)或while(true)方式,给Vector中添加数组
		int maxScore = 0;
		for(;;) {
			System.out.println("请输入学生成绩(以负数代表输入结束)");
			int score = scan.nextInt();
			if (score<0) {
				break;
			}
			if (score > 100) {
				continue;
			}
			//3.1 添加操作::v.addElement(Object obj)
			//jdk5.0之前:
//			Integer inScore = new Integer(score);
//			v.addElement(inScore);//多态
			//jdk5.0之后:
			v.addElement(score);//自动装箱

			//3.2 当输入是负数时,跳出循环
			
			//4.获取学生成绩的最大值
			if (maxScore < score) {
				maxScore = score;
			} 
		}
		
		//5.遍历Vector,得到每个学生的成绩,并与最大成绩比较,得到每个学生的等级。
		char level;
		for (int i = 0; i < v.size(); i++) {
			Object obj = v.elementAt(i);
			//3.1 添加操作::v.addElement(Object obj)
			//jdk5.0之前:
//			Integer inScore = new Integer(score);
//			v.addElement(inScore);//多态
			//jdk5.0之后:
			int score = (int)obj;//自动拆箱
			
			if(maxScore - score <= 10){
				level = 'A';
			}else if(maxScore - score <= 20){
				level = 'B';
			}else if(maxScore - score <= 30){
				level = 'C';
			}else{
				level = 'D';
			}
			System.out.println("student-" + i + " score is " + score + ",level is " + level);
			
		
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值