Lecture 10 Constructors
Lecture 10 Constructors
Technology
CIC-212
Java Programming
Constructors
Constructors
• a special kind of method to construct an instance
of an object from a class template
• default constructor is ClassName()
– created if the class has no constructors
• instance fields are initialized to default values
automatically (see next slide)
• overloaded constructors: same name with
different parameter lists
• use of “this” to call another constructor
Constructors
Java automatically initializes class (static) and object
(instance) fields
MyClass(int maximum) {
this.maximum = maximum;
}
Non-subclasses in Yes No No No No
other Pkg.
Static keyword
When objects of its class are declared, no copy of a static
variable is made
Instead, all instances of the class share the same static variable
When a member is declared static, it can be accessed before
any objects of its class are created, and without reference to any
object
The most common example of a static member is main().
Outside of the class in which static methods are defined, static
methods and variables can be used independently of any object.
To do so, you need only specify the name of their class
followed by the .(dot) operator
ClassName.methodName()
Static keyword
Restrictions:
Syntax
final type constName = value;
Example
final int FILE_NEW = 1;
final float PI = 3.141519;
Final Variables
Subsequent parts of the program may use the above
final variables FILE_NEW and PI
class A { class B {
final int X = 10; final int X = 10;
public static void main (String args[]) public static void main(String args[]) {
{ X = 20;
System.out.println(“ X is “+X); System .out. println(“ X is “+X);
} }
} }
final variable
should not change
Other Uses Of final