Java面向对象之object类自带的方法解析(equals与==、toString方法、instanceof方法、参数传递问题)

一、equals与==

1、简单说明
==:是用来判断两个变量、对象是否相等(数值、内存地址);
equals:用来判断两个对象是否相等,可以通过自己重写equals方法的逻辑,使其从类的从很多个角度进行比较。

2、用equals比较对象的内容是否相同

class Test07_Whale{
    
    
	String name;
	String color;
	//定义鲸鱼的构造方法
	public Test07_Whale(String name, String color){
    
    
		this.color = color;
		this.name = name;
	}
	
	//重写提供的默认equals方法:专门判别颜色是否相等
	public boolean equals(Test07_Whale tw){
    
    
		if(this.color == tw.color){
    
    
			return true;
		}else{
    
    
			return false;
		}
	}
	
	//定义主方法
	public static void main(String[] args){
    
    
		Test07_Whale tw1 = new Test07_Whale("蓝鲸", "蓝色");
		Test07_Whale tw2 = new Test07_Whale("蓝鲸", "蓝色");
		
		System.out.println(tw1.equals(tw2));
	}
}

1.2.1

二、toString方法

1、简单说明
(1)字符串格式化输出,即为取得对象信息,返回该对象的字符串表示形式;

(2)默认输出对象时,就是执行了toString方法的输出;

(3)默认的toString返回:包+类名@内存地址。

2、重写toString

class Test07_Whale{
    
    
	String name;
	String color;
	//定义鲸鱼的构造方法
	public Test07_Whale(String name, String color){
    
    
		this.color = color;
		this.name = name;
	}

	//重写toString方法
	public String toString(){
    
    
		return "我是一只" + this.color + "的" + this.name;
	}

	//定义主方法
	public static void main(String[] args){
    
    
		Test07_Whale tw1 = new Test07_Whale("蓝鲸", "蓝色");
		
		System.out.println("默认输出:" + tw1);
		//System.out.println("toString输出:" + tw1.toString());
		System.out.println("重写toString输出:" + tw1.toString());
	}
}

2.2.1

三、instanceof方法

1、简单说明

  • 用于判断xx对象是什么类型的;
  • 使用格式:对象名 instanceof 类名;,返回值是布尔型。

2、测试练习

class Test07_Mammal{
    
      //创建一个哺乳动物类
	//哺乳动物类的公有方法
	public void speeking(){
    
    
		System.out.println("动物正在说话……");
	}
}

public class Test07_Whale extends Test07_Mammal{
    
    
	public static void main(String[] args) {
    
    
		Test07_Mammal tm = new Test07_Mammal();  //实例化哺乳动物对象
		//判断tm对象是否属于Whale鲸鱼类
		if(tm instanceof Test07_Whale){
    
     
			System.out.println("我是一只鲸鱼");
		}else{
    
    
		System.out.println("我不是一只鲸鱼" );
		}
		
		//判断tm对象是否属于哺乳动物类
		if(tm instanceof Test07_Mammal){
    
     
			System.out.println("我是一只哺乳动物");
		}else{
    
    
		System.out.println("我不是一只哺乳动物" );
		}
	}
}

3.2.1

四、参数传递

1、简单说明

  • 值传递:把变量的值作为参数进行传递,一变只会变修改的那个变量。
  • 引用传递:把整个变量作为参数进行传递,一变,相关的变量值都会变化。
  • 在Java中使用的就是值传递。

2、change方法
在这个方法中常用来重写关于改变变量值的操作。

猜你喜欢

转载自blog.csdn.net/Viewinfinitely/article/details/119982074
今日推荐