[Java Review] 8: Object class

The following notes are based on video series: 手把手教你用Java基础教程 - 北京尚学堂 - 马士兵

I. Object
  • Object is the root class of all classes. ex.

    1
    public class <classnanme>{}

    is equal to

    1
    public class <classnanme> extends Object{}
  • toString():

    • when connector is used, this super method is auto-executed.
    • return “\<classname>@\<hashcode>“.
    • usually overriden.
  • equals():

    • if using ==, it is actually comparing ref. address.

    • default is same as ==

    • should be overriden, ex:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      public boolean equals(Object obj){
      if (obj == null) return false;
      else{
      if (obj instanceof Cat){
      Cat c = (Cat) obj;
      if (c.color ==this color && c.height == this.height){
      return true;
      }
      }
      }
      return false;
      }
II. Casting
  • A superclass ref. can point to its subclass instance.

  • For above, it can not access new member variables in its subclass.

  • instanceof can be used to check if an instance belongs to a class or superclass.

  • upcasting: treat subclass as superclass;

    downcasting: treat superclass as subclass;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//sample application 
public class Test{
public static void main(String args[]){
Test test = new Test();
Animal a = new Animal("name");
Cat c = new Cat("catname", "blue");
Dog d = new Dog("dogname", "black");
test.f(a);
test.f(c);
test.f(d);
}

public void f(Animal a){
System.out.println("name: " + a.name);
if (a instanceof Cat){
Cat cat = (Cat)a;
System.out.println("eyecolor: " + cat.eyecolor);
} else if (a instanceof Dog) {
Dog dog = (Dog)a;
System.out.println("furcolor: " + dog.furcolor);
}
}
}
0%