Wednesday, 28 July 2010
Variables
byte x,y,z; /* 08bits long, not assigned, multiple declaration */ short numberOfChildren; /* 16bits long */ int counter; /* 32bits long */ long WorldPopulation; /* 64bits long */ float pi; /* 32bit single precision */ double avagadroNumber; /* 64bit double precision */ boolean signal_flag; /* true or false only */ char c; /* 16bit single Unicode character */
Constant variables
Variables can be made constant or read only by prepending the modifier final to the declaration. Java convention uses all uppercase for final variable names.
Local Variables
Local variables (also known as automatic variables) are declared in methods and in code blocks. The automatic variables are not automatically initialized.
A java programmer should explicitly initialize them before first use. These are automatically destroyed when they go out of scope.
Field Variables and Local Variables Field variables are variables that are declared as members of classes. Local variables, also referred to as automatic variables, are declared relative to (or local to) a method or constructor. <
Automatic Initialization Note
Field variables and the elements of arrays are automatically initialized to default values. Local variables are not automatically initialized. Failure to initialize a local variable results in a compilation error.
Primary or primitive data types in java
There are 4 primary classes of primary data types in java
Integers
Floats
Boolean
Characters
There are eight primitive types in Java. Four of them are integer types; two are floating-point number types; one is the character type char, used for code units in the Unicode encoding schem; last 1 is boolean.
Default Values for various data types.
Inheritance in java
The Object class is the highest superclass (ie. root class) of Java. All other classes are subclasses (children or descendants) inherited from the Object class. The Object class includes methods such as:
| clone() | equals() | copy(Object src) | finalize() | getClass() |
| hashCode() | notify() | notifyAll() | toString() | wait() |
Inheritance in Java
Java uses the extends keyword to set the relationship between a parent class and a child class. For example using our Box class from notes about class :
public class GraphicsBox extends Box
The GraphicsBox class assumes or inherits all the properties of the Box class and can now add its own properties and methods as well as override existing methods. Overriding means creating a new set of method statements for the same method signature (name, number of parameters and parameter types). For example:
private int left, top;
// override a superclass method
public int displayVolume()
{
System.out.println(length*width*height);
System.out.println("Location: "+left+", "+top);
}
When extending a class constructor you can reuse the superclass constructor and overridden superclass methods by using the reserved word super. Note that this reference must come first in the subclass constructor. The reserved word this is used to distinguish between the object's property and the passed in parameter.
{
super (l,w,h);
this.left=left;
this.top=top;
}
public void showObj()
{ System.out.println(super.showObj()+"more stuff here");
The reserved word this can also be used to reference private constructors which are useful in initializing properties.
Special Note:You cannot override final methods, methods in final classes, private methods or static methods.
See Further
Inheritance : cpp vs java
Using super in java
Multilevel inheritance : Calling order of Constructors
Abstract classes
Interfaces in java
Multiple inheritance in java
Inheritance among interfaces in java
Multiple inheritance in java
Abstract classes : cpp vs java
Abstract classes vs Interfaces
Abstract-Interface or skeletal implementations
Various interfaces
Preventing inheritance
Final keyword in java
A java variable can be declared using the keyword final. Then the final variable can be assigned only once. You cannot be modify it afterwards. However it can be used in different contexts.
Following are the places where final can be used:
- variables: a final variable can be set once and only once.
blank final variable - A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it. - fields: a final field can also be set only once, by the constructor of the class which defines it.
- methods: a final method cannot be overridden nor hidden.
final parameters - values of the parameters cannot be changed after initialization. - classes: a final class cannot be extended or inherited.
Other effects of final:
- Java local classes can only reference local variables and parameters that are declared as final.
- A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance.
Notice how using final is an entirely negative act. The final keyword works by subtracting, limiting default language mechanisms: the ability to override a method, to set a variable or a field. The motivations behind using final fall into three broad categories: correctness, robustness, and finally performance. Seeing them 1 by one.
Final Variables
Final variables come in handy in mostly three situations:a) Declare Constants
Coupled withstatic, final is used to flag constants. This usage is well-known to all Java programmers, so I won't expand much on it. It is useful to know that the value of a field declared constant in that manner will be computed statically if possible, at compile-time. private static final int ERROR_CODE = 1 + 3 * 4 / 2;
public static final String ERROR_MESSAGE = "An error
occurred with code=" + ERROR_CODE;
b) Final Parameters
The following sample declares final parameters:public void doSomething(final int i, final int j){
// ...
}
final is used here to ensure the two indexes i and j won't accidentally be reset by the method. It's a handy way to protect against an insidious bug that erroneously changes the value of your parameters. Generally speaking, short methods are a better way to protect from this class of errors, but final parameters can be a useful addition to your coding style. Note that final parameters are not considered part of the method signature, and are ignored by the compiler when resolving method calls. Parameters can be declared final (or not) with no influence on how the method is overriden.
c) Anonymous Local Classes
The third situation involving final variables is actually mandated by language semantics. In that situation, the Java compiler won't let you use a variable unless it is declared final. This situation arises with closures, also known as anonymous local classes. Local classes can only reference local variables and parameters that are declared final.public void doSomething(int i, int j){
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};//note the semicolon here
}
The reason for this restriction becomes apparent if we shed some light on how local classes are implemented. An anonymous local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee in place, the local class is assured that its internal copies of the variables accurately reflect the actual local variables.
2. Final Fields
A final field can be assigned once and only once, and must be initialized by every constructor of the class that declares it. It is also possible to assign the field directly, in the same statement where it is defined. This simply reflects the fact that such shortcut assignments are compiled into a synthetic constructor. E.g. both the following code samples are correct and strictly equivalent; the first is preferred for being shorter. Initializing outside constructor bodypublic class MyClass{
//initializing hereitself
private final int i = 2;
}
Initialising in constructor body
public class MyClass{
private final int i;
public MyClass()
{
i = 2;
}
}
3. Using final to Prevent Method Overriding
While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to
do so, a compile-time error will result.
Methods declared as final can sometimes provide a performance enhancement: The compiler is free to inline calls to them because it “knows” they will not be overridden by a subclass. When a small final method is called, often the Java compiler can copy the bytecode for the subroutine directly inline with the compiled code of the calling method, thus eliminating the costly overhead associated with a method call. Inlining is only an option with final methods. Normally, Java resolves calls to methods dynamically, at run
time. This is called late binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding.
4. Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.Here is an example of a final class:
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.
CPP vs Java on Final – Controversy
‘final’ should not be called as constants. Because when an array is declared as final, the state of the object stored in the array can be modified. You need to make it immutable in order not to allow modifcations. In general context constants will not allow to modify. In C++, an array declared as const will not allow the above scenario but java allows. So java’s final is not the general constant used across in computer languages.
A variable that is declared static final is closer to constants in general software terminology. You must instantiate the variable when you declare it static final.
Definition as per java language specification (third edition) – 4.12.4 is “A final variable may only be assigned to once.”(§4.1.2). See notes on final w.r.t Java memory model here -
- Final in old Java memory model (click on links)
- Final in new Java memory model (click on links)
Java language specification tries to redefine the meaning of constant in the following way!
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).
Immutable Objects
Final is used to construct immutable objects in java. See – Immutable Objects
Declarations and Access Control - Java
Declaring arrays:
For example,use eitherint[] x;or
int x[];Both are legal positions for the brackets. To declare a multidimensional array, use multiple sets of brackets, e.g.
int i[][]; declares a two dimensional array. Note that, for example, int[]i[]; is also legal, and means the same thing. In Java, multidimensional arrays can be "not square" i.e. they are just arrays of arrays, and each of those constituent arrays can be of a different size. Construct arrays:
Arrays are objects. Use thenew keyword to construct them. For example having declared an array i: int[] i;you then construct the array and assign it to i as follows:
i = new int[10];The size of the array is in the brackets (in this example 10). It is common to do both operations in one statement:
int i[] = new int[10];
To initialize an array using loop iteration:
An example:int array[] = new int[15];
for(int j=0; j
array[j]=j;
}
Write code to initialize an array using the combined declaration and initialization format:
An example:char c[]= new char[] {'a','b','c','d','e'};or you can usechar c[]= {'a','b','c','d','e'};Some terms and their synonyms:
Scope/Visibility: Where something can be seen / is accessable from.Nested/Inner Class: A class whose code sits inside the body of another 'outer' class. It exists 'inside' the class in that it can see the private methods and variables.
Instance/Member: Means the method/variable/nested class belongs to each object which is an instance of the class. The term 'a member' is often used to refer to both methods and variables of this type. Cannot be accessed by statically i.e. without having an instance of the class.
Class/Static: The method/variable/nested class belongs to the class as opposed to the instances of the class. Can be used without creating an instance of the class, but static methods/nested class cannot use instancts variables/methods.
Local/Automatic variable: A variable which is declared within a method or as a parameter to the method. Cannot be seen outside the method.
Scoping Types
"default" or "friendly" - this is where no modifier is used. Means something is only visible to classes in the same package.protected - can only be accessed by classes in the same package or subclasses of this class. This frequently surprises experienced developers, especially those with a prior backround in the mutant hybrid of object orientated programming and assembly language known as 'C++' :-) To fair the name is misleading, as it sounds like it restricts access, where as it in fact it adds subclasses outside the package to the list of things that can access the item in question, as compared to using "default" access. public - can be accessed by any other class. private - can only be accessed from inside the class. Declare classes using the modifiers public, abstract or final:
public - is visible outside of its package. Without this modifier, the class cannot be accessed outside its package. abstract - cannot be instantiated, is allowed to contain abstract methods. final - cannot be subsclassed. Using the modifiers private, protected, public, static, final, native or abstract:
private - can only be accessed from inside the class. Private members are not inherited by subclasses. Inner classes can be declared private. protected - can only be accessed by classes in the same package or subclasses of this class. public - can be accessed by any other class. static - belongs to the class rather than any particular instance of the class. For variables, effectively, there is just one copy of this variable for all instances of the class, and if an instance changes the value, the other instances see that new value. For methods, it means the method can be called without having created an instance, but within the methodd you cannot use the this keyword, or refer to instance variables and methods directly (without creating an instance and referring to the variable/class in that instance). For inner classes, it means they can be instantiated without having an instance of the enclosing class, but as with static methods, the methods of the inner class cannot refer to instance variables or methods of the enclosing class directly. final - cannot be changed. Variables are constants, methods cannot be overridden, classes cannot be subclassed. Since Java1.1 you can declare the variable without assigning a value. Once you assign a value, you cannot change it. The are known as 'blank' finals, are frequently used for things like constants you wish to initialise from a configuration file. native - a method which is not written in java and is outside the JVM in a library. abstract - a method which is not implemented. Must be implemented in a subclass if that subclass is to be 'concrete' and allow people to instantiate it. Nested Classes
To define a non-static nested class either in a class or method scope:
Place the class definition (for the nested class) inside another class definition (the outer class) or a method.To define, in method scope, an anonymous nested class that implements a specified interface:
An anonymous nested class is defined where is it instantiated (in a method). An anonymous nested class must either implement an interface or extend a class, but theimplements or extends keywords are not used. For example the following line causes the method to return an object which is an instance of an anonymous nested class: return new SomeClass() { /*body of the anonymous class goes here*/ };You might like to think of an anonymous nested class as part of a really long new statement, which happens to contain a class definition, and which is why it has a ";" at the end. The following example calls someMethod(), passing an instance of the anonymous nested class: someMethod(new SomeClass() { /*body of the anonymous class goes here*/ });In both cases SomeClass() is not the name of the anonymous class (anonymous means it has no name) rather is it the name of the class that you are extending or the interface you are implementing. These classes cannot define a constructor, as they do not have a name that you can use to declare the constructor method. If SomeClass() is a class, the default constructor of that class is called, if you want to use a non-default constructor instead, you supply arguments e.g.: return new SomeClass(12) { /*body of the anonymous class goes here*/ };will call the SomeClass constructor which takes an int.Write code in a non-static method of the outer class to construct an instance of the nested class.
Inner x = new Inner(); constructs an instance of Inner where Inner is a nested class defined in the current class. Write code to construct an instance on a nested class where either no this object exists, or the current this object is not an instance of the outer class.
You must create an instance of the outer class first. Given a class, Outer, containing a nested class Inner: Outer.Inner y = new Outer().new Inner();The above creates an instance of Inner called y, but it had to construct an instance of Outer first. The following example creates the Outer instance on a separate line, the syntax in the second line is the one you use when you already have an instance of the outer class.
Outer x = new Outer();If Inner is static, you can use:
Outer.Inner y = x.new Inner();
Outer.Inner I= new Outer.Inner();
State which variables and methods in enclosing scopes are accessible from methods of the inner class.
A non-static inner class has access to all member variables and methods of the containing class. If the inner class is defined inside a method, it has access to those method (a.k.a. automatic or local) variables which are declaredfinal, in addition to the above. A static inner class is restricted in the same way as a static method: it cannot refer to instance variables and methods of the containing class directly (without creating an instance and referring to the variable/class in that instance).
| For a given class, determine if a default constructor will be created and if so state the prototype of that constructor. |
classname() where classname is the name of you class. A default constructor is automatically created only if you do not create any constructors in your class. If you create a non-default constructor (i.e. one that takes an argument), then you may have to create a default one yourself, if you want there to be one. All constructors call the default constructor of its parents class (if there is one), and so on up the hierarchy to Object, unless you specify a different constructor using
super(...) (to use a constructor in the parent) or this(...). If you use such calls, they must be the first thing in the constructor.
Literals
|
|
Escape (aka backslash) sequences are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape sequence starts with a backslash. The available sequences are:
| Seq | Usage | Seq | Usage |
|---|---|---|---|
| \b | backspace | \\ | backslash |
| \f | formfeed | \" | double quote |
| \n | newline | \' | single quote |
| \r | carriage return | \### | Octal encoded character |
| \t | horizontal tab | \uHHHH | Unicode encoded character |