Java Static and Final Keyword

Posted on November 12, 2012. Filed under: java/j2EE |


final keyword is import for security coding.
As a general rule, all classes should be final if they do not need to be extended. At least, we should make as much methods final as possible. Why, because subclass or anonymous class can change any behavior your class exposed to outside.

======
InnerClass>ls
OuterClass.java OuterClassDrive.java
InnerClass>cat OuterClass.java
public class OuterClass {
final private String aSecrete = “a secrete”;
public void display() {
System.out.println(aSecrete);
}

//private InnerClass in = new InnerClass();

public void doBusiness() {
new InnerClass().innocentMsd();
}

class InnerClass {
public void innocentMsd() {
System.out.println(“no harm”);
}
}
}

InnerClass>cat OuterClassDrive.java
public class OuterClassDrive {
OuterClass o = new OuterClass() {
final private String aSecrete = “a secrete?”;
class InnerClass {
public void innocentMsd() {
System.out.println(“no harm?”);
}
}
public void doBusiness() {
new InnerClass().innocentMsd();
}
public void display() {
System.out.println(aSecrete);
}
};

void doEvil() {
System.out.println(“normal object”);
OuterClass on = new OuterClass();
on.doBusiness();
System.out.println(“Evil Object”);
o.new InnerClass().innocentMsd();
o.doBusiness();
o.display();
}

public static void main(String…args) {
OuterClassDrive drive = new OuterClassDrive();
drive.doEvil();
}
}

InnerClass>javac *.java
InnerClass>ls
OuterClass$InnerClass.class OuterClassDrive$1.class
OuterClass.class OuterClassDrive.class
OuterClass.java OuterClassDrive.java
OuterClassDrive$1$InnerClass.class
InnerClass>java OuterClassDrive
normal object
no harm
Evil Object
no harm
no harm?
a secrete?
InnerClass>
======

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: