The Java valley is always under the threat. So all the masters must be prepared all the time.
It wasn’t solely Po’s unwavering determination that led to Master Shifu’s decision to anoint him as the master, as we read in Chapter 1. Astonishingly, Master Oogway had perceived something extraordinary in Po, a hidden secret concealed within a chest safeguarded in the enigmatic depths of the Temple’s secret chamber. The chamber itself remained a clandestine sanctuary, known only to Master Shifu, shrouded in mystery and concealed from the prying eyes of any other master.
In the mystical land of Java Valley, there was a grand gathering of martial artists from different clans. Each clan had its own unique set of skills and techniques. The gathering was organized by the Java Clan, known for their mastery of nested classes and nested interfaces.
The Java Clan believed in the power of encapsulation and wanted to organize their skills in a hierarchical manner. They used nested classes and nested interfaces to achieve this goal. The nested classes represented different levels of mastery within the clan, while the nested interfaces represented specific skill sets.
Within the Java Clan, there was a class called GrandMaster
. This class served as the outer class and contained several nested classes and nested interfaces. Each nested class represented a different level of mastery, from Novice to Master, while each nested interface represented a specific skill, such as Swordsmanship or Meditation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class GrandMaster {
// Nested class representing Novice level
class Novice {
// Novice level skills and techniques
}
// Nested class representing Apprentice level
class Apprentice {
// Apprentice level skills and techniques
}
// Nested class representing Master level
class Master {
// Master level skills and techniques
}
// Nested interface representing Swordsmanship skill
interface Swordsmanship {
// Swordsmanship techniques
}
// Nested interface representing Meditation skill
interface Meditation {
// Meditation techniques
}
}
The Novice, Apprentice, and Master classes represented different levels of mastery within the Java Clan. Each class had its own set of skills and techniques that were taught to the members of the clan at that particular level.
The Swordsmanship and Meditation interfaces represented specific skills that were highly valued within the Java Clan. These interfaces defined the techniques and methods that needed to be mastered in order to become a true warrior of the Java Clan. By incorporating the Meditation
interface, the Java Clan emphasizes the importance of mental well-being and the benefits it brings to their martial arts practice.
1
2
3
class Warrior implements GrandMaster.Swordsmanship, GrandMaster.Meditation {
// Implement Swordsmanship and Meditation techniques
}
Warriors of the Java Clan, such as the Warrior
class, could implement these nested interfaces to showcase their proficiency in specific skills. By implementing these interfaces, the Warrior
class gained access to the techniques and methods defined within the interfaces.
The use of nested classes and nested interfaces allowed the Java Clan to organize their skills and techniques in a structured and hierarchical manner. It provided clarity and encapsulation, ensuring that each level of mastery and each skill set had its own dedicated space within the clan.
In conclusion, the Java Clan utilized nested classes and nested interfaces to organize their skills and techniques in a hierarchical manner. The nested classes represented different levels of mastery, while the nested interfaces represented specific skill sets. This organizational structure allowed the clan members to showcase their proficiency in different skills and techniques, ultimately making them formidable warriors in the land of Java Valley.
The nested interfaces Swordsmanship
and Meditation
allowed the Java Clan to define specific skill sets within their martial arts practice. By nesting these interfaces within the GrandMaster
class, the Java Clan could group related interfaces and limit their scope to the context of the GrandMaster
class. This ensured that these skills were encapsulated within the martial arts practice of the Java Clan and provided a clear contract for future warriors to implement and master these skills.
📌 Info
You know a class or an interface can be created inside a method too.
Enum
Enums can be used to represent the different ranks, directions, or even the emotions experienced by the warriors during their journey. For example, the Java Clan could use an enum to represent the different directions, such as NORTH, SOUTH, EAST, and WEST, which could be used to navigate through the martial arts techniques and strategies.
By using enums, the Java Clan can ensure that the values of these essential aspects of their martial arts practice are fixed and cannot be changed. This provides a clear and consistent way to represent these values throughout the decision making process and discussions.
New warriors undergo hard training sessions. During these training sessions, different emotions can arise, and the Java Clan wants to handle each emotion differently.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public enum Emotion {
CALM {
@Override
public void handleSituation() {
// Handle situation for calm emotion
System.out.println("Stay focused and maintain inner peace.");
}
},
ANGRY {
@Override
public void handleSituation() {
// Handle situation for angry emotion
System.out.println("Channel your anger into controlled power.");
}
},
PEACEFUL {
@Override
public void handleSituation() {
// Handle situation for peaceful emotion
System.out.println("Embrace the serenity and harmonize your movements.");
}
};
public abstract void handleSituation();
}
During the hard training sessions, the Java Clan can invoke the handleSituation()
method based on the emotion experienced by the new warriors. It helps to examine if a warrior is ready for the next phase.
Be Anonymous
📌 Info
Anonymous classes in Java are a specific type of nested class. They are defined without a name and can be created inside another class or interface. Anonymous classes often extend subclasses or implement interfaces.
In the Java Clan, there exists a Warrior Pool, which holds the responsibility of providing warriors for battle. However, creating an instance of a warrior is not an easy task and can consume a significant amount of time, which is not affordable during war. To address this challenge, a separate community called the Warrior Pool was created to manage the pre-existing images provided by each master. Before handing over a warrior to the villagers for combat, the Warrior Pool employs a special technique to sanitize all the images, ensuring they are safe and free from any potential vulnerabilities.
To standardize the sanitation process, a separate entity called SecretsSanitizer was established. The Warrior Pool community opted for an anonymous approach to apply the standard sanitation process with their own logic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public interface SecretsSanitizer {
default Warrior sanitize(Warrior warrior){
return warrior;
}
}
public class WarriorPool {
public Warrior giveWarrior() {
// Take warrior image from the available pool
SecretsSanitizer secretsSanitizer = new SecretsSanitizer() {
@Override
public Warrior sanitize(Warrior warrior) {
// Remove any manuscript
// Remove the knowledge about the secret chamber
return warrior;
}
};
Warrior warrior = // Retrieve warrior from the pool
// Sanitize the warrior before giving it to the villagers
Warrior sanitizedWarrior = secretsSanitizer.sanitize(warrior);
return sanitizedWarrior;
}
}
Over time, they realized the need to make the process more generic and designated a separate entity responsible for sanitizing the secrets. This shift allowed the Warrior Pool to focus more on the pooling process and invoke various types of sanitizers without requiring knowledge of their specific workings.
As part of their improvement efforts, the Warrior Pool also decided to shift the sanitation process to occur when an image is assigned to the pool, rather than when it is required. This change aimed to increase availability and streamline the overall workflow.
There were still many places where anonymous practice of creating classes were being used. For example; Java Clan wants to handle the situation when a warrior is feeling overwhelmed during training.
1
2
3
4
5
6
7
Emotion.OVERWHELMED {
@Override
public void handleSituation() {
// Handle situation for overwhelmed emotion
System.out.println("Take a moment to breathe and regain focus.");
}
}.handleSituation();
If you don’t know, anonymous classes are useful in situations where you need to create a class that has a specific implementation for a single-use scenario. They are commonly used when you need to override a method or provide a unique implementation for a particular behavior or to introduce additional methods or fields within the context of the anonymous class.
If you need to create multiple instances of a class or require access to its constructor, a local class might be more appropriate
You can freely create a local class for the same functionality. But as Java suggest to maintain the correct hierarchy and encapsulation, a local class which have no other use than to be used in a method for single time purpose, can be created as anonymous class. Once, you realize that the functionality you implemented in anonymous class can be reused on different places then you can separate the code and make a local class.
Be Generic
Po was given the responsibility to manage the library. The library that Po was entrusted with was a grand structure nestled in the heart of the village. Its towering walls were adorned with intricate carvings depicting scenes of ancient battles and wise sages imparting their knowledge. The entrance, guarded by stone lions, led to a vast hall filled with shelves upon shelves of books, scrolls, and manuscripts.
At the heart of the library lay the restricted section, a chamber shrouded in an air of mystery. Here, the most treasured and delicate scrolls were kept, representing the ancient martial arts techniques that had been passed down through generations. The room was dimly lit, with soft rays of sunlight filtering through stained glass windows, casting colorful patterns on the polished wooden floors.
It was within this sacred space that Po’s friends, the village warriors and scholars, gathered to discuss their dreams and aspirations. They saw in Po a kindred spirit, someone with a passion for knowledge and a burning desire to leave his mark on the world. Encouraged by their unwavering support, they convinced Po that he had the potential to become a great master by contributing his own literature to the library.
With their words echoing in his mind, Po felt a surge of determination coursing through his veins. He imagined himself standing amongst the ancient scrolls, sharing his wisdom and insights with future generations. The thought of leaving a lasting legacy, a testament to his growth and understanding, inspired him to embark on this ambitious journey.
But the road to becoming a great master was not without its challenges. Doubts crept into Po’s mind, whispering tales of inadequacy and fear of failure. It was during these moments of uncertainty that his friends became his pillars of support, reminding him of his unique perspective and the value he could bring to the library.
One day, after hours of contemplation, Po’s mind was buzzing with excitement. He had come up with a brilliant idea to contribute to the library. Determined to make it a reality, he woke up early in the morning, the sun barely peeking over the horizon. The village was still shrouded in a hazy mist, and the air was filled with the aroma of freshly brewed tea.
Po quietly slipped out of his bed, careful not to disturb his sleeping companions. With a sense of purpose in his heart, he made his way to his father’s noodle shop. The door creaked open, and Po found his father, Mr. Ping, already hard at work, kneading the dough and preparing the ingredients for the day’s noodles.
As Po approached his father, a mischievous glimmer danced in his eyes. He knew that convincing Mr. Ping to share the secret recipe of his famous noodles would not be an easy task. Po rolled up his sleeves and jumped into action, offering his assistance in any way he could. With each chop of vegetables and stir of the simmering broth, Po’s determination grew stronger.
The villagers, still rubbing the sleep from their eyes, began to notice Po’s unusual behavior. Whispers spread through the village as they wondered why the young panda was so eager to help his father. Some speculated that he had stumbled upon a hidden treasure, while others believed he had fallen in love with a mysterious stranger. The curiosity surrounding Po’s early morning activities added an extra layer of intrigue to the tale.
Day after day, Po continued to wake up early, working side by side with his father. The villagers couldn’t help but be captivated by the dedication and passion that emanated from the noodle shop. They marveled at the aroma of the noodles that wafted through the air, tempting their taste buds and drawing them closer to the shop.
As Po’s relationship with his father blossomed, so did his understanding of the secret recipe. Mr. Ping, impressed by his son’s unwavering commitment, decided it was time to pass down the closely guarded knowledge. Together, they perfected the art of noodle-making, infusing each strand with love, tradition, and a touch of magic.
With the secret recipe in his possession, Po felt a surge of confidence as he embarked on his journey to the library. Little did he know that his adventure was about to take an unexpected turn.
Time was passing quickly, and it was Po’s last day in the library. He hastily wrote down the secret noodle recipe and rushed to the library to submit his scroll before closing time. Master Shifu, the wise guardian of the library, had a keen eye for detail and was quick to spot any inconsistencies.
When Po presented his scroll to Master Shifu, the atmosphere was charged with anticipation. The room fell silent as Master Shifu unrolled the scroll, his eyes scanning the words and illustrations. Suddenly, a look of surprise crossed his face, followed by a burst of laughter. The scroll was filled with comical errors and nonsensical martial arts techniques.
Po’s cheeks flushed with embarrassment as he realized his mistake. He had been so focused on the excitement of contributing to the library that he had neglected to understand the concept of type safety. He approached Master Shifu in a mild voice and asked what type safety meant. Master Shifu, though initially amused, took this opportunity to teach Po a valuable lesson. Master Shifu calmed down and gathered all the masters in the classroom.
Master Shifu showed a toy with holes of different shapes on the top: square, circle, and triangle. In his other hand, he held wooden shapes. He explained to all the masters, “Even though each shape is meant to be passed through a specific hole, they can be inserted into the box through the circle hole due to improper type checking.”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.ArrayList;
import java.util.List;
class Shape {
// Common properties and methods of all shapes
}
class Square extends Shape {}
class Circle extends Shape {}
class Triangle extends Shape {}
class ToyBox<T> {
private List<T> toys;
public void addToy(T toy) {
toys.add(toy);
}
public void playWithToys() {
// for (T toy : toys)
}
}
class Palace {
public static void main(String[] args) {
ToyBox<Square> squareToyBox = new ToyBox<>();
squareToyBox.addToy(new Square());
ToyBox<Circle> circleToyBox = new ToyBox<>();
circleToyBox.addToy(new Circle());
ToyBox<Triangle> triangleToyBox = new ToyBox<>();
triangleToyBox.addToy(new Triangle());
playWithToyBoxes(squareToyBox);
playWithToyBoxes(circleToyBox);
playWithToyBoxes(triangleToyBox);
}
public static void playWithToyBoxes(ToyBox<? extends Shape> toyBox) {
toyBox.playWithToys();
}
public static void insertToToyBox(ToyBox<? super Circle> toyBox, Circle circle) {
toyBox.addToy(circle);
}
}
Master Shifu, the guardian of the palace, spoke with authority, emphasizing the importance of type safety within its walls. He drew a metaphor, comparing the concept to a quiver filled with arrows. “In this palace, type safety is like a vigilant archer ensuring that the right arrows are used in the right situations,” he explained, his voice resonating with wisdom.
Referring to the incident of the scroll type mismatch indirectly, Master Shifu delved into a detailed explanation of type safety. To illustrate his point, he reached into the quiver and retrieved an arrow, holding it up for everyone to see. “Each arrow is meticulously crafted for a specific purpose, be it to strike with precision or to create a non-lethal impact,” he began.
He then showcased another arrow, explaining its unique properties. “This arrow is coated with chemicals that ignite upon reaching the peak of its trajectory, generating intense heat,” he described. “And this arrow, with a hammerhead, is designed to repel enemies without causing harm. Each arrow requires a distinct bow, crafted specifically for its purpose.”
Master Shifu emphasized the significance of ensuring type safety in weaponry, drawing a parallel to the need for proper usage of programming constructs. “Just as a bow must be matched with the appropriate arrow, it is essential to maintain type safety in programming, ensuring that each component is correctly utilized at the right time,” he concluded, leaving a lasting impression on Po and his fellow learners.
The metaphor of arrows and bows served as a vivid representation of the consequences that could arise from neglecting type safety. It conveyed the importance of understanding and adhering to the principles of type safety, protecting against potential errors and ensuring the smooth functioning of programs, just as the archer safeguards the integrity of their arsenal.
📌 Info
The JRE leverages type safety for performance optimizations by eliminating unnecessary type checks during runtime.
What do you think? Am I talking about Po or Tigress or someone new?
Actually it doesn’t matter if you fill in “Po” or “Tigress” in all three blanks, the sentence will still make sense.
Using Po: Master Shifu is teaching a secret martial skill to Po. Through rigorous training and discipline, Po will master this technique and become a formidable warrior. With Po’s dedication and determination, success is inevitable.
Using Tigress: Master Shifu is teaching a secret martial skill to Tigress. Through rigorous training and discipline, Tigress will master this technique and become a formidable warrior. With Tigress’s dedication and determination, success is inevitable.
This is how Generics work. For an example, consider a cross training module where a master can teach other master with his skills.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Trainer<T extends Master> {
private List<T> trainers;
public void addTrainer(T trainer) {
trainers.add(trainer);
}
public void train(T master) {
// Training logic goes here
System.out.println("Training " + master.getClass().getSimpleName());
for (T trainer : trainers) {
System.out.println("Trained by " + trainer.getClass().getSimpleName());
}
}
}
Now suppose I want to ensure that Po and Tigress can teach each other. Master Shifu can teach both but they’re not teaching Master Shifu;
1
2
3
4
5
for (T trainer : trainers) {
if (!trainer.getClass().isAssignableFrom(master.getClass())) {
System.out.println("Trained by " + trainer.getClass().getSimpleName());
}
}
All the masters must be ready for the battle, and it can happen only when all help each other. Some generic weapons and generic strategy might be useful in the battle field. Hope! we’ll win the battle.
I tried to cover the concepts or rather need of nested classes, Enum, anonymous classes, and generics through the story of KungFu Java. Some of the topics may need more depth to understand their use. However, I was more focused to explain their need.
This article is basically for absolute beginners or for entertainment purpose.
Your feedback is really important. So I can improve my future articles and correct what I have already published. You can also suggest if you want me to write an article on particular topic. If you really like this blog, or article, please share with others. That's the only way I can buy time to write more articles.