On Java 1.8, you don't have to define a field as final
to it be acessed from anonymous classes.
For example, on older versions:
public void foo(final int bar) {
new Runnable() {
public void run() {
System.out.println(bar);
}
};
}
But, now, on Java 1.8, bar
does not need to be final:
public void foo(int bar) {
new Runnable() {
public void run() {
System.out.println(bar);
}
};
}
So, if I compile my project, and the only resource implemented on Java 1.8 I'm using is this (I'm not using any lambdas, new classes, etc), will my code be executable on computers with older Java versions? If not, why?
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.
18) Which of the following is true about the anonymous inner class? Explanation: Anonymous inner classes are the same as the local classes except that they don't have any name. The main use of it is to override methods of classes or interfaces.
When compiling with -target 1.8
, javac
will emit class files with a version number of 52.0
which is not supported by previous JVMs. So even if that’s the only difference it prevents you from executing files compiled with -target 1.8
.
And javac
doesn’t support specifying -source 1.8
and -target 1.7
at the same time. It will produce the error message source release 1.8 requires target release 1.8
.
But indeed, if using effectively final variables is the only Java 8 feature you are using, there is no byte code difference besides the version number. If you compile such code targeting 1.8
and patch the class files reducing the version number to 51.0
they will run on Java 7. It’s as simple as reducing the byte at index 7 by one.
The tricky part is to discipline yourself to not using other Java 8 features when using a Java 8 compiler if you want to create Java 7 compatible code…
I think Java 8 changed the class file major version to be different than Java 7 so an older JVM probably won't be able to load the newer classes.
If you compile with a -target 1.7, I don't know if you can use effectively final
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With