Compsci 230 S2 2017 Programming Techniques: Static & Dynamic Binding
Compsci 230 S2 2017 Programming Techniques: Static & Dynamic Binding
Compsci 230 S2 2017 Programming Techniques: Static & Dynamic Binding
Programming Techniques
Static & Dynamic Binding
Agenda & Reading
Topics:
Static & Dynamic Binding
Casting
Reading
Java how to program Late objects version (D & D)
Chapter 10
The Java Tutorial
Creating and Using Packages
http://docs.oracle.com/javase/tutorial/java/package/packages.html
Controlling Access to Members of a Class
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Overriding and Hiding Methods
http://docs.oracle.com/javase/tutorial/java/IandI/override.html
Hiding Fields
http://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
2 Lecture12
1.Introduction
If you have more than one method of same name (method
overriding) or two variable of same name in same class hierarchy it
gets tricky to find out which one is used during runtime as a result of
there reference in code.
This problem is resolved using static and dynamic binding in Java.
Binding is the process used to link which method or variable to be
called as result of the reference in code.
Most of the references is resolved during compile time but some
references which depends upon Object and polymorphism in Java is
resolved during runtime when actual object is available.
When a method call is resolved at compile time, it is known as static
binding, while if method invocation is resolved at runtime, it is known as
Dynamic binding or Late binding.
3 Lecture12
1.Introduction
private, final and static methods and variables uses static binding and
resolved by compiler because compiler knows that they can't be
overridden and only possible methods are those, which are defined
inside a class, whose reference variable is used to call this method.
Static binding uses Type information for binding while Dynamic
binding uses Object to resolve binding.
Static Binding
Variables – static binding
Variables are resolved using static binding which makes there execution fast because no
time is wasted to find correct method during runtime.
Private, final, static methods – static binding
Overloaded methods are resolved using static binding
Dynamic Binding
Overridden methods are resolved using dynamic binding at runtime.
4 Lecture12
Python
x = 10;
Java
Java is a “type-safe” language. int x = 10;
x = "Hello";
5 Lecture12
2.Static Typing Restrictions
Variables
A reference variable of static type T can refer to an instance of class T
or to an instance of any of T’s subclasses
The is-a relationship applies only up the hierarchy from a subclass to its direct
(and indirect) superclasses, and not down the hierarchy.
Cup c = new EspressoCup();
CoffeeCup c1 = new EspressoCup();
EspressoCup c2 = new EspressoCup();
Cup c3 = new CoffeeMug();
CoffeeCup c4 = new CoffeeMug();
CoffeeMug c5 = new CoffeeMug();
Cup c6 = new TeaCup();
7 Lecture12
3.Static Binding – Variables
Instance variables
Static binding only uses Type information
Access to fields is governed by the type of the reference
For example: class Base { public class Derived extends Base {
public int x = 10; public int y = 20;
} }
8 Lecture12
3.Static Binding – Variables
Two variable of same name
Static binding only uses Type information
Access to fields is governed by the type of the reference
class Base2 { public class Derived2 extends Base2 {
public int x = 10; public int x = 20;
} }
For example:
a field that has the same name as a field in the superclass hides the
superclass's field
Derived b2-> x=10
Case 1: a Derived object with a Derived reference x=20
//Case 1: instance variable x from Derived (20)
Derived2 b1 = new Derived2();
System.out.println("b1.x=" + b1.x);
Case 2:b3aistype
Derived
declared as
Base
object with a Base(superclass) reference
instance variable x from Base, (10)
//Case 3: Base b3-> x=10
Base2 b2 = new Derived2();
System.out.println("b2.x=" + b2.x); x=20
9 Lecture12
3.Static Binding – Variables
Get the hiding values
Within the subclass, the field in the superclass cannot be
referenced by its simple name
To "unshadow" it by referring to super.x
public class Derived extends Base { method In the
... subclass
public void method1() {
System.out.println("x from Derived:" + x);
System.out.println("x from superclass: " + super.x);
...
Note:
this.x access the field name x, defined in the child class
super.x access the field name x, defined in a parent class
super.super.x is not valid
x was not specified as private.
10 Lecture12
3.Static Binding – Variables
Static Variables
Static binding only uses Type information
Access to fields is governed by the type of the reference
Class variable: one copy only, all instances of the class share the
same static variable public class Derived3 extends Base3
public static int y=20;
{
class variables:
one copy only
System.out.println("Derived3.y=" + Derived3.y);
System.out.println("Derived3.y=" + Derived3.x); Base3.x=10
Derived3.y=20
Derived3.y=10
11 Lecture12
3.Static Binding
private, final and static methods
A final method in a superclass cannot be overridden in a
subclass.
Methods that are declared private are implicitly final, because it’s
not possible to override them in a subclass.
Methods that are declared static are implicitly final.
A final method’s declaration can never change, so all
subclasses use the same method implementation, and calls to
final methods are resolved at compile time—this is known as
static binding.
12 Lecture12
3.Static Binding
static Methods
Only the non-static methods of a class can be overridden
Example: public class Derived4 extends Base4 {
public static int x = 20;
class Base4 { public static void get() {
public static int x = 10; System.out.println("static:Derived:get");
public static void get() { }
System.out.println("static:Base:get"); }
}
}
Derived4.get(); static:Base:get
static:Derived:get
13 Lecture12
3.Static Binding
private Methods
When you declare a method in a Java class, you can allow or
disallow other classes and object to call that method.
class Base5 {
private void get() {
System.out.println("private:Base:get");
}
}
14 Lecture12
3.Static Binding
final Methods
You use the final keyword in a method declaration to indicate
that the method cannot be overridden by subclasses.
class Base6 {
public final void get() {
System.out.println("final:Base:get");
}
}
15 Lecture12
3.Static Binding
Overloading Methods
The practice of defining two or more methods within the same class
that share the same name but have different signatures is called
overloading methods.
The signature of a method is comprised of its name, its parameter types and the
order of its parameters.
The signature of a method is not comprised of its return type nor its visibility.
class Base7 {
public void aMethod() {
System.out.println("called aMethod()");
}
public void aMethod(int x) {
System.out.println("called aMethod(x)");
}
public static void main(String[] args) {
Base7 b1 = new Base7();
b1.aMethod(8);
} called aMethod(x)
}
16 Lecture12
4.Dynamic Binding
Dynamic Binding refers to the case where compiler is not able to
resolve the call and the binding is done at runtime only.
Java compiler can't be sure of what type of object this reference would be
pointing to at runtime.
Polymorphism in Java is resolved during runtime when actual object is
available. class Base8 {
public void g() {
public class Derived8 extends Base8
public void g() {
{
public void g() { public void g() {
Example: }
System.out.println("Base:g");
}
System.out.println("Derived:g");
} }
18 Lecture12
5.Casting Wider type
Primitive Types
Widening conversions
Wider assignment Casting
needed
Wider Casting
Casting a value to a wider value is always permitted but never required. However,
explicitly casting can make your code more readable
double d = 4.9; d1 = i; Assignment conversion
int i = 10; d1 = 10.0
double d1, d2;
d2 = (double) i; Casting conversion
(optional)
d2 = 10.0
Narrowing conversion
Narrow assignment – Compile-time error
Narrow Casting – Loss of information
You must use an explicit cast to convert a value in a large type to a smaller type, or
else converting that value might result in a loss of precision.
Assignment conversion
double d = 4.9; //i1 = d; Compile-time error
int i = 10;
int i1, i2; Narrow Casting: i2=4
i2 = (int) d; NOTE: Everything beyond the decimal point will be truncated
19 Lecture12
5.Casting Example: casting/CastObject.java
Note:
Reference conversion, like primitive conversion, takes place at compile time,
because the compiler has all the information it needs to determine whether
the conversion is legal
Inheritance relation is an “is a” relation; the parent object is more general
than child object
20
The general rule of thumb is that converting to a superclass is permittedLecture12
(because super class is wider than sub class)
Person
5.Casting
Wider type Example: casting/CastObject.java
Narrowing conversion
Narrow object reference assignment – Compile-time error
Narrow object reference casting –
Compile-time OK,
Run-time?
Like primitive casting: By using a cast, you convince the compiler to let you do a
conversion that otherwise might not be allowed
The run-time check determines whether the class of the object being cast is compatible
with the new type
Base b-> x=10
Compile-time error
Base b = new Base(); //d1 = b;
Derived d = new Derived(); Compile-time OK, Run-time ERROR
d2 = (Derived) b; b is an instance of class Base, not Derived
Derived d1, d2, d3;
java.lang.ClassCastException: Base
Base d_as_b = new Derived(); d3 = (Derived) d_as_b; Compile-time OK, narrow casting,
casting from superclass to subclass
Using Casting
Shadowing
Using type casting, it is possible to recover a hidden member (class variable,
class method, or an instance variable), but not an overridden method (i.e. an
instance method). An overridden method can be recovered only by means of
a super call in derived class
class Base2 { public class Derived2 extends Base2 {
public int x = 10; public int x = 20;
} }
x=20
22 Lecture12
Hiding
Person
5.Casting Student Employee
Rules
TertiaryStudent CollegeStudent
At compile-time, checking is carried out to determine whether the cast-type
and the type of the existing reference variable are related through inheritance.
At run time, a check is made to determine whether the object actually pointed
to is compatible with the cast-type.
Compile- Run-
Student s1 = new TertiaryStudent();
time time
TertiaryStudent s2 = new TertiaryStudent();
(TertiaryStudent) s1 OK OK
Employee e1 = new Employee();
(TertiaryStudent) s2 OK OK
Student s3 = new CollegeStudent();
Student s4 = new Student();
(TertiaryStudent) e1 ERROR
(TertiaryStudent) s3 OK ERROR
(TertiaryStudent) s4 OK ERROR
(Students) S2 OK OK
23 Lecture12
Summary
Student s = new Student();
Object Conversion Person p = s;
Make it possible to reference an object in a different way by assigning it to
an object reference of a different type.
It is handled automatically by the compiler.
The object is NOT converted or changed in any way. Once instantiated, an
object NEVER changes its type (a Cat will always be a Cat). The concept is
similar to the "widening conversions" performed on primitive data types.
Casting
It is needed when the compiler doesn't recognize an automatic conversion.
The concept is similar to the casting of primitive data types to perform a
"narrowing conversion".
Casting does not change the reference or the object being pointed to. It only
changes the compiler’s treatment of the reference
Casting is only legal between objects in the same inheritance hierarchy
You can safely cast from an object to its superclass
24 Lecture12
Exercise 1
What is the output?
Base01 b = new Base01();
Derived01 d = new Derived01();
25 Lecture12
class Base01 {
public int x = 10;
Structure static int y = 10;
Base01() {
x = y++;
Base01 & Derived01 }
public int foo() {
return x;
}
public static int goo() {
return y;
}
}
26 Lecture12
Overriding, hiding, and overloading
methods
An instance method in a subclass with the same signature (name, plus
the number and the type of its parameters) and return type as an
instance method in the superclass overrides the superclass's method.
If a subclass defines a class method with the same signature as a class
method in the superclass, the method in the subclass hides the one in
the superclass.
The distinction between hiding and overriding has important implications.
The version of the overridden method that gets invoked is the one in the subclass.
The version of the hidden method that gets invoked depends on whether it is invoked
from the superclass or the subclass.
Overloaded methods are differentiated by the number and the type of
the arguments passed into the method.
The compiler does not consider return type when differentiating methods, so
you cannot declare two methods [in the same class] with the same signature
even if they have a different return type.
27 Lecture12
class Base02 {
public int x = 10;
Exercise 2 static int y = 10;
Base02() {
x = y++;
Base2, Derived2 }
public int foo() {
return x;
}
public static int goo() {
return y;
}
}
28 Lecture12
Exercise 2
What is the output?
Derived02 d = new Derived02();
System.out.println("The Derived object");
System.out.println("d.x = " + d.x); // hide
System.out.println("d.y = " + d.y);
System.out.println("d.foo() = " + d.foo()); // override
System.out.println("d.goo() = " + d.goo());
Base02 b = new Derived02();
System.out.println("\nThe Derived object");
System.out.println("b.x = " + b.x);
System.out.println("b.y = " + b.y);
System.out.println("b.foo() = " + b.foo()); // override
System.out.println("b.goo() = " + b.goo());
class Base04 {
int i = 1;
public int f() { class Derived04 extends Base04 {
return i; int i = 2; // shadows i in Base04
} public int f() { // override f() in Base04
} return -i;
}
}
30 Lecture12