Java 25 Example: FlexibleConstructors
In Java 8
/*In java 8 the super constructor is needed to be the first call in child class constructor (if needed)*/ Super constructor gets first call in child constructor, this is not flexible-code, that means if super class is getting initialized even before initializing the child class, if child class initialization failed then super class constructor is created and will be useless.
public class FlexibleConstructors {
public static void main(String[] args) {
try {
Cat cat = new Cat(true, "Russian Bob Cat");
System.out.println("Animal Details: " + cat.breed + "--" + cat.domestic);
Cat lion = new Cat(false, "African Lion");
System.out.println("Animal Details: " + lion.breed + "--" + lion.domestic);
} catch (IllegalArgumentException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
class Animal {
final String breed;
Animal(String breed) {
this.breed = breed;
}
}
class Cat extends Animal {
final boolean domestic;
Cat(boolean domestic, String breed) {
super(breed); /* <------- Super constructor gets first call in child constructor, this is not flexible-code */
if (!domestic) {
throw new IllegalArgumentException("We need only domestic cats");
}
this.domestic = domestic;
}
}
In Java 25
/*But in java 25 the super constructor can be the used anywhere in child class*/ Super constructor gets flexible-call in child constructor, this is flexible-code, that means if child class is not getting initialized correctly then no need to call super class.
public class FlexibleConstructors {
public static void main(String[] args) {
var cat = new Cat(true, "Russian Bob Cat");
System.out.println("Animal Details: " + cat.breed +"--"+ cat.domestic);
var lion = new Cat(false, "African Lion");
System.out.println("Animal Details: " + lion.breed +"--"+ lion.domestic);
}
}
class Animal{
final String breed;
Animal(String breed){
this.breed = breed;
}
}
class Cat extends Animal{
final boolean domestic;
Cat(boolean domestic, String breed) {
if(!domestic){
throw new IllegalArgumentException("We need only domestic cats");
}
this.domestic = domestic;
super(breed); /* <------- */
}
}
If you face any issue to run this code, just for your information this feature in Java is still in preview — you need to enable this while compilation.
First copy the code and create a file with any name like
Place the file inside the
Then run the following commands:
Then simply run the program with:
First copy the code and create a file with any name like
FlexibleConstructors.java
Place the file inside the
jdk-25/bin/
folder.Then run the following commands:
javac --enable-preview --release 25 FlexibleConstructors.java
Then simply run the program with:
java --enable-preview FlexibleConstructors
(pransukh.21@gmail.com)
Comments
Post a Comment
Thanks in anticipation.