Chapter 4

hierarchical relationship

  • In hierarchy, there is ‘is-a’ relationship.
  • Superclass is called when it is at top, the one below is called subclass.
  • At superclass, there is interface class
    public interface name<> {
        public void methodname();
        ...
    }
    
    1. in interface class, it lists all abstract methods
    2. subclass can implement interface, as promising class will contain all methods listed in interface class
      => interface inheritance, which subclass inherits signatures(method name, input and output type and value), but not implementation
      => implementation inheritance, which subclass can inherit signatures and implementation.
      • use default keyword to specify a method that subclass should inherit from interface
        -> it means any class implements this superclass can use this method.
      • it follows dynamic method selection, which means there is a default method created in interface class, and its subclass overrides this default method, when calling this method, it will follow method of subclass.
      • the override method is called at runtime is determined by the run-time type or dynamic type.
      • compiler determine whether or not something is valid based on the static type(compile-time) of object.
  • The extends keyword can also be used for inheritance relationship. One class can extends another class without changing its original functionality. Subclass can inherit all members of the parent class.
    • All instance and static variables
    • All methods
    • All nested classes
    • constructors and private members are not inherited
      • since constructors are not inherited, then in subclass it needs to call its superclass’s constructors
        • without explicitly call to superclass’s argument constuctor, it will call constuctor with no argument.
        • super(); <- way to call superclass constuctor

overriding vs. overloading

Overriding:

  • happen on inheritance relationship, only with exact same method name and signatures.
  • follow dynamic method selection
  • annotation @override -> help to proofreading and prevent typos
    Overloading:
  • happen anytime, same method name but different signatures
  • do not follow dynamic method selection
  • check static type and call method

casting

  • a tool to tell compiler not to do type-checking, return the type as declared.
  • but it can lead to runtime exception

Commentaires

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×