Programming Fundamentals in Java
Programming Fundamentals in Java
Day 2 (Afternoon)
Tuesday 27 October 2020 | 2pm
Contents
• Static members
• Shadowing
• this
• Example
• Constructors in Child Classes
• Super
• this()
Static members
STATIC MEMBERS
• Let’s imagine a class Coordinate that stores two data members x and y.
• The Coordinate class has a constructor that sets the x and y values.
• The Coordinate class also defines a method that prints the coordinate.
• What happens when we create an object from this class?
STATIC MEMBERS
• So coordinate1 has its own x and y values, and coordinate2 also has its own x and y
value.
• This means that when you instantiate an object, you make a copy of the members
declared within the relevant class.
STATIC MEMBERS
• The example below shows the effect of declaring unit in Coordinate class as static.
• Following from Shadowing, what if we wanted to use the global data member instead?
• We can explicitly state this using the “this” notation.
• foo() now prints 10 instead of 20.
Example
EXAMPLE
• When we create an object from a class that inherits another, the constructors of the
parent classes will be called too.
• In the earlier example, we created an object from class Two.
• Class Two inherits class One.
• So when we create the new object from class Two, the constructor of class One is
called followed by the constructor of class Two.
Super
SUPER
• Remember how classes may have more than one constructor provided they have
different signatures?
• Let’s apply that to class One from the previous example.
• How does the constructor in Two know which parent constructor to call?
• Before we can answer that question, we must understand what Super() will do.
SUPER
• So in this case, super() (with no arguments) will call the corresponding constructor in
the parent class One with no arguments.
• Note: this will work without super() too since Java will invoke the default constructor
of the parent class inherently.
• If we call super with one integer as an argument, it will call the corresponding
constructor in the parent.
⛔
this()
THIS()