Local class or classes in Java are defined in a block, which is a group of zero or more statements between balanced braces. We typically find local classes defined in the body of a method. We can define a local class in Java inside any block. In this example we will create a local class to validate email address using regex pattern or regular expression.
For example, we can define a local class in a method body, a for loop, or an if clause.
A local class in Java has access to the members of its enclosing class. In addition, a local class in Java has access to local variables. However, a local class can only access local variables that are declared final.
When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter.
Starting from Java SE 8, a local class can access local variables and parameters of the enclosing block that are final
.
Local classes are similar to inner classes because they cannot define or declare any static members.
Local classes are non-static because they have access to instance members of the enclosing block.
We are supposed not to declare static initializers or member interfaces in a local class.
A local class can have static members provided that they are constant variables.
For example, we can validate an email address using local class by the following source code.
package com.roytuts.local.clazz;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LocalClassExample {
static String regularExpression = "^([a-zA-Z0-9])+([a-zA-Z0-9\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$";
public static void validateEmail(String email1, String email2) {
class EmailAddress {
Pattern pattern;
Matcher matcher;
EmailAddress(String email) {
pattern = Pattern.compile(regularExpression);
matcher = pattern.matcher(email);
}
public boolean validate() {
return matcher.matches();
}
}
EmailAddress emailAddress1 = new EmailAddress(email1);
EmailAddress emailAddress2 = new EmailAddress(email2);
if (emailAddress1.validate())
System.out.println(email1 + " is valid.");
else
System.out.println(email1 + " is invalid.");
if (emailAddress2.validate())
System.out.println(email2 + " is valid.");
else
System.out.println(email2 + " is invalid.");
}
public static void main(String[] args) {
validateEmail("soumitra", "soumitrajuster@email.com");
}
}
By executing the above program you will get the below output:
soumitra is invalid.
soumitrajuster@email.com is valid.
Source Code
You can download source code.
Thanks for reading.