

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to programming concepts in java, focusing on polymorphism, method overloading, and method overriding. Polymorphism allows for multiple methods with the same name but different signatures or the same name and signature in an inheritance chain. Overloading refers to methods with different signatures, while overriding involves methods with the same signature. The document also covers the concept of final methods that cannot be overridden and the potential confusion of shadowing variables with the same name in a subclass.
Typology: Study notes
1 / 2
This page cannot be seen from the preview
Don't miss anything!


with Java, for Beginners
Polymorphism- Overloading- OverridingMore overriding (inheritance)
CIS
1
Polymorphism means
many
(poly)
shapes
(morph)
In Java, polymorphism refers to the fact that you can havemultiple methods with the same name in the same class
There are two kinds of polymorphism:
Overloading
¾
Two or more methods with
different signatures
Overriding
¾
A method in a subclass to “override” a method in the superclassthat has the
same signature
We’ve already seen Overloading scenario with Constructors
E.g. public RealVector(double x, double y) {..}
public RealVector(double mag, Angle theta) {..}
CIS
2
Method
overloading
occurs when
A class has two or more methods with the same
name
but
different
signatures
¾
Different signature -> the number, order, or types of theirparameters differ
// the foo method is overloadedpublic void foo() {.. }public void foo(int x) { ..}public void foo(int x, double y) {..}
When the foo(..) method is called, Java picks the one that
“matches”. E.g.
foo(10, 350.5);
CIS
3
¾
It can be
overriden
in a subclass simply by creating a
method with the same signature
public String toString() {. .}
CIS
4
Some Methods cannot be overwritten
class Animal {
final boolean canMove(int direction) { ... }
} class Rabbit extends Animal {
// inherits but cannot override canMove(int)
CIS
5
Overriding Variables
One in child class is called shadow variable
¾
It shadows the variable with same name in the parent class
Confuses everyone!
There's no good reason to declare new variable withthe same name
CIS
6
Example
class Animal {
protected String type;public Animal(){
type = "Animal"; }
Dog d = new Dog();> d.type //can field as not set privateDog
public class Dog extends Animal{
String type;public Dog(){
type = "Dog";
} }
CIS
7
Some Variables Cannot be Shadowed