1. 程式人生 > 其它 >Java 物件多型equals toString 方法覆寫

Java 物件多型equals toString 方法覆寫

技術標籤:javajava

package com.msc.example;
class TestA{
    private String name;
    private int age ;
    public TestA() {} ;
    public TestA(String name,int age){
        this.name = name ;
        this.age = age ;
    }
    @Override
    public boolean equals(Object obj){
        if(!(obj instanceof
TestA)) return false ; if(obj == null) return false ; if(this == obj) return true ; TestA ta = (TestA) obj; return this.name.equals(ta.name) && this.age == ta.age ; } @Override public String toString() { return "Test{" + "name='"
+ name + '\'' + ", age=" + age + '}'; } } class TestB { private String name; private int age; public TestB() { } public TestB(String name, int age) { this.name = name; this.age = age; } } public class JavaPoly { public
static void main(String[] args) { TestA ta = new TestA("張三",20) ; TestA tab = new TestA("張三",20) ; TestA tac = new TestA("張三",21) ; TestB tb = new TestB("里斯",22); TestB tba = new TestB("里斯",22); System.out.println(ta); System.out.println(tb); System.out.println(ta.equals(tab)); System.out.println(ta.equals(tac)); System.out.println(tb.equals(tba)); System.out.println("--------多型----------"); Object obj = new int []{1,2,3} ; //向上轉型 if(obj instanceof int[]){ int data[] = (int []) obj ; //向下轉型 for(int temp : data){ System.out.println(temp+"、 "); } } } }

輸出
在這裡插入圖片描述