Java 6 Refresher

JDK 4 introduced the assert keyword

JDK 5 introduced generics, autoboxing, enumerations, var-args, enhanced for loop.

New keywords in Java

assert (since 1.4)
enum (since 1.5)

keywords to watch out for

const
strictfp
goto

JavaBean standard for getter and setter for boolean:

getXXX
setXXX / isXXX

JavaBean standard for getter and setter for listners:

addXXXListener(XXXListener xxxlistener)
removeXXXListener(XXXListener xxxlistener)

The strictfp non access modifier

Applicable to class and method
Marking a class strictfp means that any method code in the class/method will conform to a floating point standard without relying on the underlying operating system.

Points to note:

All variables declared in an interface are implicitly “public static final”
All methods in an interface are implicitly “public abstract”
An interface implicitly is always abstract
An interface method cannot be static since interface methods are meant to be overrridden and static methods cannot be overridden.
Interface methods cannot be native/strictfp
Abstract classes have to be explictly declared “abstract”
An interface may have public/default access modifiers just like classes
An interface can exend more than one interfaces
Abstract classes can extend other abstract classes
Abstract classes can implement one or more interfaces.
Abstract classes can never contain private methods since all its methods are meant to be overridden.
A native method must end with a semicolon with the implementation omitted.
Native methods are implemented in platform dependent code.

Flavors of the final modifier

final methods cannot be overrridden
final variables cannot change the value assigned to them
final classes cannot be extended
final references cannot be used to reference another object
*final reference variables must be initialized before the constructor completes

the abstract modifer cannot be combined with the static modifier for methods since abstract implies overriding while static methods cannot be overrridden.

“synchronized” modifier applies to code blocks and methods
*”sychronized” can be combined with static/ final

class TestFinalVar {
	public void testFinalVar(final int a, final int b) {// a and b cannot be
														// reassigned //within
														// this method
		System.out.println(a + b);
	}

	public static void main(String args[]) {
		TestFinalVar tfv = new TestFinalVar();
		tfv.testFinalVar(2, 3);
	}
}

Var-args:
Things to remember:
Only one var-arg is allowed in a list of arguemnts
A var-arg always has to be the last in a list of arguments.
var-args can be part of arguments to a constructor
more on var-args…

Note:
Negative numbers in Java are represented by 2’s complement notation:
1. subtract 1
2. take 1’s complement of the result(replace 1 with 0 and vice versa)

byte(8 bits=1 byte)
short(16 bits=2 bytes)
int(32 bits-4 bytes) float(4 bytes-signed)
long(64 bits=8 bytes) double(8 bytes-signed)
boolean is OS dependent

Variables are always created on the stack while objects on the heap

Transient variables:
By declaring a variable transient you are asking the JVM to skip it during serialization

Volatile variables:
These are used to transmit single variables between threads. Synchronized blocks are preferred to volatile variables. Volatile vars will never use local copies. They will use shared memory for reading and writing. If you want to transfer two or more variables there is a risk that reading will be done while the writing has not yet finished. “volatile” indicates that the var may be used by other threads.

Nested classes:

An inner class can be static/ non-static/ abstract/ final/ public/ private/ protected
A method local class can be instantiated only inside a method where it is defined, a local block, a static initializer or an instance intializer (need more info)
It cannot access the local vars of the enclosing method unless they are declared final. The only modifier for a method local class is abstract/ final

class Outer {
	static class StaticNested {
		public void print() {
			System.out.println("Hallo World");
		}
	}

	public static void main(String[] args) {
		Outer.StaticNested ou = new Outer.StaticNested();
                // instance of StaticNested is not required.
		ou.print();
	}
}

As a separate class:

enum TShirtSize {// enum as a separate class
	SMALL, MEDIUM, LARGE,
}

public class TShirtTest {
	public void print() {
		TShirtSize tss = TShirtSize.SMALL;
		System.out.println("I always wanted " + tss);
	}

	public static void main(String args[]) {
		TShirtTest tt = new TShirtTest();
		tt.print();
	}
}

D:\java6\work>java TShirtTest
I always wanted SMALL

As a separate class:

enum ShirtSize {// enum as a separate class
	SMALL, MEDIUM, LARGE,
}

class Shirt {
	ShirtSize ss;
};

public class ShirtTest {
	public void print() {
		Shirt shirt = new Shirt();
		shirt.ss = ShirtSize.LARGE;
		System.out.println("I always wanted " + shirt.ss);
	}

	public static void main(String args[]) {
		ShirtTest tt = new ShirtTest();
		tt.print();
	}
}
D:\java6\work>java ShirtTest
I always wanted LARGE

As a class member:

class BallTest {
	enum Ball {// enum as a a class member
		SMALL, MEDIUM, LARGE,
	}

	public void print() {
		System.out.println("I always wanted " + Ball.MEDIUM);
	}

	public static void main(String args[]) {
		BallTest bt = new BallTest();
		bt.print();
	}
}
D:\java6\work>java BallTest
I always wanted MEDIUM

*Enum declarations outside a class must not be marked static/ final/ abstract/ private/ protected

enum with a constructor and method

enum Weight {// enum with a constructor and method
	LIGHT(20), MEDIUM(40), HEAVY(80);// note semicolon
	Weight(int pounds) {
		this.pounds = pounds;
	}

	public int getPounds() {// method
		return pounds;
	}

	private int pounds;;// instance var after enum value declaration
}

public class WeightTest {
	public static void main(String args[]) {
		Weight bert = Weight.LIGHT;
		Weight amy = Weight.MEDIUM;
		Weight brown = Weight.HEAVY;
		System.out.println(bert.getPounds() + "  " + amy.getPounds() + "  "
				+ brown.getPounds());
	}
};
D:\java6\work>java WeightTest
20  40  80

The compiler looks only at the reference type, not the instance type. At runtime the actual instance is looked up. Only overridden instance methods are dynamically invoked based on the real object’s type. Not static methods, not variables. But which overloaded version of the method to be called is decided at based on the reference type of the argument passed at compile time.

class Parent {
	public void study() throws Exception {
	}
};
class Child extends Parent {
	public void study() {
	}
}
public class CompilerVsRuntimeTest {
	public static void main(String[] args) {
		Parent p = new Parent();
		Child c = new Child();
		Parent pc = new Child();
		c.study();// ok
		pc.study();// compiler sees exception thrown
	}
}
D:\java6\work>javac CompilerVsRuntimeTest.java
CompilerVsRuntimeTest.java:17: unreported exception java.lang.Exception; must be
caught or declared to be thrown
pc.study();//compiler sees exception thrown
^
1 error
class Parent {
	public void groan() {
		System.out.println("Grooooooan");
	}
};
class Child extends Parent {
	public void groan() {
		System.out.println("Yeaaaaaaaaaaah!!");
	}

	public void play() {
		System.out.println("Will I be called?");
	}
};
public class InheritanceTest {
	public static void main(String[] args) {
		Parent p = new Parent();
		Parent c = new Child();// Child is the father of man?
		p.groan();
		c.groan();
		c.play();
	}
}
D:\java6\work>javac InheritanceTest.java
InheritanceTest.java:22: cannot find symbol
symbol  : method play()
location: class Parent
c.play();
^
class Parent {
	public void groan() {
		System.out.println("Grooooooan");
	}
};

class Child extends Parent {
	public void groan() {
		System.out.println("Yeaaaaaaaaaaah!!");
	}

	public void play() {
		System.out.println("Will I be called?");
	}
};

public class InheritanceTest {
	public static void main(String[] args) {
		Parent p = new Parent();
		Parent c = new Child();// Child is the father of man?
		p.groan();
		c.groan();
		// c.play();
	}
}
D:\java6\work>java InheritanceTest
Grooooooan
Yeaaaaaaaaaaah!!
class Parent {
};

class Child extends Parent {
};

public class OverloadTest {
	public void doStuff(Parent p) {
		System.out.println("Parent version");
	}

	public void doStuff(Child c) {
		System.out.println("Child version");
	}

	public static void main(String[] args) {
		Parent p = new Parent();
		Parent c = new Child();// Child is the father of man?
		OverloadTest ot = new OverloadTest();
		ot.doStuff(p);
		ot.doStuff(c);
	}
}
D:\java6\work>java OverloadTest
Parent version
Parent version

As of Java5 you are allowed to change the return type of the overriding method as long as the new return type is a subtype of the declared return type of the superclass method.

A class that implements an interface must follow all the rules for legal overrides for the methods it implements.

Only static variables and methods can be accessed as part of the call to super() or this().

This is because instance methods cannot be run before the super() call returns.

Loose coupling and tight cohesion

Playing with constructors

Child.java

public class Child extends Parent {
	static String staticNameVar = "NoNameYet";
	int ageInstanceVar = 5;

	Child(String name, int age) {
		this(name);
		System.out.println("My name is " + name + " and I am " + age
				+ " years old");
		doingThis("playing");
	}

	Child(String name) {
		super(doingThis("Studying"));// only static methods can be called before
										// constructor completes
		System.out.println("My name is " + name);
	}

	public static String doingThis(String activity) {
		System.out.println("I am " + activity);
		return ("Had enough of " + activity);
	}

	public static void main(String[] args) {
		Child child = new Child("Amy", 19);
	}

}
class Parent {
	Parent(String msg) {
		System.out.println("I am your parent; my message is " + msg
				+ ". Is it?");
	}

	Parent() {
		System.out.println("I am your parent I have no message for you");
	}
};
/**
Output ->

I am Studying
I am your parent; my message is Had enough of Studying. Is it?
My name is Amy
My name is Amy and I am 19 years old
I am playing

*/

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Comments are closed.

%d bloggers like this: