Java: Class Methods Part 2

Overloading Overridding Constructor Finalizer

Also see Part 1 about Methods








Overloading Methods

  • Have multiple methods of the same name but have different parameters either in number or type.

Example



Overriding Methods

  • This is the way in which methods that are inherited from a classes ancestors in the inheirantence chain are replaced or over-ridden by new methods.
  • Even if you have created a method that overrides a superclass's method, you can still call this superclasses method by using the following:
           super.method(); 
Exercise



Constructor Methods

  • optional method, a default exists that does nothing.
  • Special Kind of method called when creating an instance of a class that may perform any variety of operations including initializing variables, creating other objects, etc.
  • Always have the same name as the class.
  • Can have multiple constructors (overloaded) that take different inputs and can perform different operations.
  • Has NO return type.
  • If you write a class with a constructor with parameters and you intend to possibly use it as a Pareny class you need to make sure you also write a constructor with NO paramters. This is needed because: If the child class is defined with no constructors, it will automatically call super() which is the Parent's constructor with no arguments.
  • Inside of a constructor, if you need to call the parents constructor, you can do so by simply adding the following line inside of your constructor:
          super(arg1, ....); 

Exercise



Finalizer Methods

  • Called just before the object is garbage-collected and its memory reclaimed. Must be defined as follows:
     protected void finalize() throws Throwable { ...}
    NOTE: the throws Throwable refers to errors/exceptions that could occur....we will discuss this later when we talk about exceptions!!!
  • The default finalize() does nothing.
  • You can call a parent's finalize() using:
        super.finalize();
  • You can call finalize() yourself...it will not call the garbage collector.