TYPES, VALUES AND VARIABLES(9)
TYPES, VALUES AND VARIABLES(9)
Where types are used:
Types are used in declarations and expressions. Each of the usage below will be covered in subsequent blogs:
1. declarations:
- in imported types
- in fields
- as method parameters
- as method results (what a method returns)
- as constructor parameters
- as local variables
- as exception handler parameters
- as type variable
2. expressions
- class instance creation expressions
- generic class instance creation
- array creation
- generic method and constructor invocation
- casts
- the instanceof operator
- the arguments to parameterized types
VARIABLES:
A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type or a reference type.
All assignments to a variable are checked for assignment compatibility, usually at compile time but when involving arrays, a run-time check is made.
Variables of primitive types: these variables always hold a value of that exact primitive type.
Variables of reference types: let T be our reference type.
If T is a class type. It holds the following values:
A. a null reference e.g T var = null;
B. a reference to an instance of class T. e.g T secondvar = new T();
C. a reference to any class that is a subclass of T e.g
package api_package;
public class T {…}
public class Tsub extends T{…}
public class Loader {
public static void main(String[] args) {
T avar = new T();
Tsub anovar = new Tsub();
avar = anovar;
}
}
if T is an interface type, it can hold the following values:
a. a null reference
b. a reference to any instance that implements the interface.
public interface IT {}
public class T implements IT{}
public class Loader {
public static void main(String[] args) {
T avar = new T();
IT newvar = avar;
}
}
Note that a variable of type, array of T, T[], where
1. T is a primitive type can hold the following values:
a. a null reference
b. a reference to any array of type, T[]
public class Loader {
public static void main(String[] args) {
int[] nob = null;
int[] hope = nob;
}
}
2. T is a reference type, then a variable of type T[ ] can hold:
a. a null reference
b. a reference to any array of type, array of S, S[], such that type S is a subclass or subinterface of type T.
public class T implements IT{}
public class Tsub extends T{}
public class Loader {
public static void main(String[] args) {
T[] var = null;
var = new Tsub[1];
}
}
A variable of type Object[] can hold any array of any reference type.
A variable of type Object can hold:
a. a null reference
b. a reference to any object, whether class instance or array.
No comments:
Post a Comment