Overloading과 Overriding
Overloading
Overloading: allows different methods to have same name but different signature
-
different signature: number/type of input paramters, or both
-
a.k.a. compile time polymorphism, static polymorphism, early binding
-
method call determined at compile time
Ways of method overloading in Java
- changing the number of parameters
- changing data types of arguments
- changing order of parameters of methods
Compile time polymorphism
Polymorphism: objects' capacity to take several forms
Compile time polymorphism
- resolved during compilation process
- method definition & method call are linked during compile time
- achieved by method overloading & operator overloading
- actual object is not used for binding
- program execution is faster than late binding
Overriding
Overriding: allows a subclass or child class to provide a specific implementation of a method already provided by its super-classes or parent classes
- when a method in subclass has same name & parameters/signature & return type as a method in super-class
- one way to achieve runtime polymorphism
- method call determined at runtime based on object type
- final, static, or private methods cannot be overriden
- static: defining a static method w/ same signature as a static method is method hiding
- private: private methods can't be overriden b/c they are bonded during compile time
Use super to call parent class method in overriding method.
Runtime Polymorphism
Runtime polymorphism (= Dynamic method dispatch): process in which a call to an overriden method is resolved at runtime rather than compile time
- an overriden method is called through reference variable of a superclass
- determination of method to be called is based on the object being referred to by the reference variable
Upcasting: when reference variable of parent class(interface) refers to object of child class
A a = new B(); // when B inherits A
Access Modifiers
The access modifier for an overriding method can allow more (BUT NOT LESS) than the overriden method
(ex) protected instance method in super-class can be overriden by a public method > made public (not private)
Abstraction과 Encapsulation
Abstraction
Abstraction: property by virtue of which only the essential details are displayed to the user
- non-essential units are displayed to the user
- process of identifying only the required characteristics of an object, ignoring irrelevant details
Encapsulation
Encapsulation: wrapping up of data under a single unit
- binds code & data together it manipulates
- a protective shield that prevents data from being accessed by code outside this shield
- variables/data of a class is hidden from any other class
- can be accessed only through member functions of its own class (where they're declared)
- data-hiding: data in a class is hidden from other classes
- can be achieved by declaring all variables in the class as private & writing public getters/setters
References: