Core Java - Surprise Test - The OOP Artisan Test: Building with Inheritance, Abstraction, and Polymorphism #104
Replies: 6 comments
-
|
PRASETHA N package com.practice.problems.java;
import java.util.ArrayList;
import java.util.List;
/**
* Main class responsible for managing the activation of the Citadel's conduits.
*/
public class CitadelRestoration {
/**
* The main method that activates various power conduits.
*
* @param args command-line arguments
*/
public static void main(String[] args) {
System.out.println("=== Citadel Power Grid Activation Sequence ===");
// PowerConduit generic = new PowerConduit("GEN-000");
List<PowerConduit> powerConduits = new ArrayList<>();
CrystalAmplifier ca1 = new CrystalAmplifier("CA-001", "Ruby");
OrganicCapacitor oc1 = new OrganicCapacitor("OC-001", "Luminous Moss");
CrystalAmplifier ca2 = new CrystalAmplifier("CA-002", "Emerald");
powerConduits.add(ca1);
powerConduits.add(oc1);
powerConduits.add(ca2);
System.out.println("\n--- Activating All Conduits ---");
for (PowerConduit conduit : powerConduits) {
conduit.activateConduit();
conduit.displayConduitStatus();
System.out.println();
}
System.out.println("\n--- Checking Specific Conduit Details ---");
for (PowerConduit conduit : powerConduits) {
if (conduit instanceof CrystalAmplifier) {
CrystalAmplifier ca = (CrystalAmplifier) conduit;
ca.setAmplificationLevel(10);
System.out.println("Tuned CrystalAmplifier " + ca.getConduitId() + ": New Amplification: "
+ ca.getAmplificationLevel() + ", Crystal: " + ca.getCrystalType() + ".");
} else if (conduit instanceof OrganicCapacitor) {
OrganicCapacitor oc = (OrganicCapacitor) conduit;
System.out.println("OrganicCapacitor " + oc.getConduitId() + " current energy: " + oc.getEnergyStored()
+ " units.");
}
}
System.out.println("\n=== Citadel Systems Partially Restored. Well done, Apprentice! ===");
}
}/**
* Abstract base class representing a power conduit in the Citadel. It contains
* shared attributes and behaviors used by all conduit types.
*/
abstract class PowerConduit {
protected final String conduitId;
protected boolean isActive;
/**
* Constructs a PowerConduit with an identifier.
*
* @param conduitId the ID of the conduit
*/
public PowerConduit(String conduitId) {
this.conduitId = conduitId;
this.isActive = false;
System.out.println("PowerConduit " + conduitId + " forged. Status: INACTIVE.");
}
/**
* Retrieves the ID of the conduit.
*
* @return the conduit ID
*/
public String getConduitId() {
return conduitId;
}
/**
* Checks whether the conduit is active.
*
* @return true if the conduit is active, otherwise false
*/
public boolean checkStatus() {
return isActive;
}
/**
* Activates the conduit. Implemented differently for each conduit type.
*/
public abstract void activateConduit();
/**
* Displays the current status (ACTIVE or INACTIVE) of the conduit.
*/
public void displayConduitStatus() {
String status = isActive ? "ACTIVE" : "INACTIVE";
System.out.println("Status of " + conduitId + ": " + status + ".");
}
}/**
* Represents a Crystal Amplifier conduit that amplifies power using crystals.
*/
class CrystalAmplifier extends PowerConduit {
private String crystalType;
private int amplificationLevel;
/**
* Constructs a CrystalAmplifier with ID and crystal type.
*
* @param conduitId the ID of the conduit
* @param crystalType the type of crystal used
*/
public CrystalAmplifier(String conduitId, String crystalType) {
super(conduitId);
this.crystalType = crystalType;
this.amplificationLevel = 0;
System.out.println("CrystalAmplifier " + conduitId + " (Type: " + crystalType + ") infused. Amplification: 0.");
}
/**
* Gets the type of crystal used in the amplifier.
*
* @return the crystal type
*/
public String getCrystalType() {
return crystalType;
}
/**
* Retrieves the current amplification level.
*
* @return the amplification level
*/
public int getAmplificationLevel() {
return amplificationLevel;
}
/**
* Sets the amplification level of the amplifier.
*
* @param level the new amplification level (non-negative)
*/
public void setAmplificationLevel(int level) {
if (level < 0) {
this.amplificationLevel = 0;
System.out.println("Warning: Amplification level cannot be negative. Set to 0 for " + conduitId + ".");
} else {
this.amplificationLevel = level;
}
}
/**
* Activates the crystal amplifier and sets default amplification.
*/
@Override
public void activateConduit() {
this.isActive = true;
this.amplificationLevel = 5;
System.out.println("CrystalAmplifier " + conduitId + " roars to life! Crystal: " + crystalType
+ ". Amplification set to 5.");
}
}/**
* Represents a biological energy conduit powered by organic biomatter.
*/
class OrganicCapacitor extends PowerConduit {
private String biomatterType;
private int energyStored;
/**
* Constructs an OrganicCapacitor with ID and biomatter type.
*
* @param conduitId the ID of the capacitor
* @param biomatterType the type of biomatter used
*/
public OrganicCapacitor(String conduitId, String biomatterType) {
super(conduitId);
this.biomatterType = biomatterType;
this.energyStored = 20;
System.out.println("OrganicCapacitor " + conduitId + " (Biomatter: " + biomatterType
+ ") synthesized. Energy Stored: 20 units.");
}
/**
* Returns the amount of energy stored.
*
* @return the current energy storage value
*/
public int getEnergyStored() {
return energyStored;
}
/**
* Activates the organic capacitor and boosts energy storage.
*/
@Override
public void activateConduit() {
this.isActive = true;
this.energyStored += 50;
System.out.println("OrganicCapacitor " + conduitId + " awakens! Biomatter: " + biomatterType
+ ". Energy surges to " + energyStored + " units.");
}
} |
Beta Was this translation helpful? Give feedback.
-
|
package test; public class PowerConduit { } } |
Beta Was this translation helpful? Give feedback.
-
|
import java.util.ArrayList; abstract class PowerConduit { } class CrystalAmplifier extends PowerConduit { } class OrganicCapacitor extends PowerConduit { } public class CitadelRestoration { } |
Beta Was this translation helpful? Give feedback.
-
|
Lohith R package org.example; import java.util.ArrayList; public class CitadelRestoration { List powerConduits = new ArrayList<>(); } } class CrystalAmplifier extends PowerConduit{ } isActive=true; |
Beta Was this translation helpful? Give feedback.
-
|
package com.edureka.test; /**
package com.edureka.test; import java.util.ArrayList; /**
|
Beta Was this translation helpful? Give feedback.
-
|
Sayan Dey - Task Completed |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Right, Apprentice! Your journey through the fundamentals of Core Java, Object-Oriented Programming, and the sacred Best Practices has been noteworthy. Master Elara has observed your progress from her sanctum within the crumbling Citadel of Computara. The Great Tangle, a chaotic mess of legacy code and forgotten conventions, still threatens to unravel the very fabric of the digital realm.
But there is hope. You.
Today, your skills will be put to a surprise test – not just of knowledge, but of application, precision, and the alchemical artistry of good code. This is The Alchemist's Legacy: A Java Trial of Blueprints, Lineage, and Ethereal Forms!
The Narrative:
The Citadel of Computara runs on various Conduits of Power. These conduits, once vibrant, are now failing. Each conduit is a specialized Java class, and their interaction is key to the Citadel's harmony. Master Elara believes that by restoring three key types of conduits and linking them to the Central Power Grid, you can begin to reverse the decay. She has handed you an ancient tablet, its surface glowing faintly with the tasks ahead.
Your Mission:
Follow the instructions on the tablet (below) to reconstruct the Conduits of Power and the Power Grid. You must do this within a single Java file named
CitadelRestoration.java. The final output of your program will be the "Proof of Restoration," which Master Elara will use to assess your work.The Tablet's Inscriptions (Your Tasks):
Chapter I: The Foundation Stone - Seals of Creation and Lines of Lineage (Constructors & Basic Inheritance)
Master Elara's Voice (from the tablet): "Every great structure, Apprentice, begins with a solid foundation. We must first define a basic
PowerConduit. This conduit will have a unique identifier and a status indicating if it's active. Then, we will craft a specialized version, aCrystalAmplifier, which inherits the essence of aPowerConduitbut adds its own crystalline properties."Your Tasks (Puzzle 1):
Create the
PowerConduitClass:conduitId(String): A unique identifier for the conduit. Make thisprotectedandfinal.final? For core identifiers that shouldn't change after creation.isActive(boolean): Represents if the conduit is currently active. Make thisprotected.publicconstructor that accepts aString conduitId.conduitIdwith the provided value.isActivetofalseby default (new conduits are not active initially)."PowerConduit [conduitId] forged. Status: INACTIVE."(Replace[conduitId]with the actual ID).public String getConduitId(): ReturnsconduitId.public boolean checkStatus(): ReturnsisActive.Create the
CrystalAmplifierClass:PowerConduit.extendskeyword for lineage.crystalType(String): The type of crystal used (e.g., "Ruby", "Sapphire"). Make thisprivate.amplificationLevel(int): The current level of amplification. Make thisprivate.publicconstructor that acceptsString conduitId,String crystalType.PowerConduitparts.super()incantation for invoking the parent's creation seal!crystalTypewith the provided value.amplificationLevelto0initially."CrystalAmplifier [conduitId] (Type: [crystalType]) infused. Amplification: 0."public String getCrystalType(): ReturnscrystalType.public int getAmplificationLevel(): ReturnsamplificationLevel.public void setAmplificationLevel(int level): Sets theamplificationLevel. If the providedlevelis negative, set it to0and print"Warning: Amplification level cannot be negative. Set to 0 for [conduitId].". Otherwise, set the level.Master Elara's Wisdom (Javadoc Hint): "Apprentice, your creations must speak for themselves, even when you are not there to explain them. Adorn your classes and public methods with Javadoc comments – the ancient script that reveals purpose, parameters (
@param), and returns (@return). This is the mark of a true Code Alchemist, ensuring clarity across ages (and for your assessors!)."Chapter II: The Ethereal Blueprint - Defining Essence and Form (Abstract Classes, Abstract & Concrete Methods)
Master Elara's Voice: "Some conduits share an essence, a common purpose, but their activation method is unique to their form. The very idea of a
PowerConduitis an 'Ethereal Blueprint' – you cannot manifest a generic one; it must always be a specific type. We must now refine ourPowerConduitto reflect this. It shall declare the intent to activate, but each specific type will define how."Your Tasks (Puzzle 2):
Modify
PowerConduitto be anabstractclass:abstractkeyword transforms a class into a blueprint that cannot be instantiated on its own.getConduitId,checkStatus) will remain. Abstract classes can indeed have these!Add an
abstractmethod toPowerConduit:public abstract void activateConduit();isActivestatus and print a type-specific activation message.Add a
concretemethod to theabstract PowerConduitclass:public void displayConduitStatus():"Status of [conduitId]: [ACTIVE/INACTIVE based on isActive field]."Implement
activateConduit()inCrystalAmplifier:@Overrideannotation.isActive(inherited fromPowerConduit) totrue.amplificationLevelto5(a default activation level)."CrystalAmplifier [conduitId] roars to life! Crystal: [crystalType]. Amplification set to 5."Create a New Concrete Subclass:
OrganicCapacitorabstract PowerConduitclass.biomatterType(String): E.g., "Luminous Moss", "Sentient Vine". Make thisprivate.energyStored(int): Amount of energy currently stored. Make thisprivate.publicconstructor that acceptsString conduitId,String biomatterType.biomatterType.energyStoredto20(initial charge)."OrganicCapacitor [conduitId] (Biomatter: [biomatterType]) synthesized. Energy Stored: 20 units."activateConduit()inOrganicCapacitor:@Overrideannotation.isActivetotrue.energyStoredby50upon activation."OrganicCapacitor [conduitId] awakens! Biomatter: [biomatterType]. Energy surges to [new energyStored] units."public int getEnergyStored(): ReturnsenergyStored.Chapter III: The Conductor's Baton - The Art of Many Forms (Dynamic Polymorphism)
Master Elara's Voice: "The true power of our alchemy lies not just in individual conduits, but in their harmonious interaction. You must now create a
PowerGrid– a central conductor that can manage any type ofPowerConduit, invoking their unique activations through a common command. This is the 'Art of Many Forms' – Polymorphism!"Your Tasks (Puzzle 3):
Create the
CitadelRestorationClass (The Main Conductor):public static void main(String[] args)method.Inside the
mainmethod ofCitadelRestoration:=== Citadel Power Grid Activation Sequence ===// PowerConduit generic = new PowerConduit("GEN-000");PowerConduitis an ethereal blueprint!java.util.Listthat can holdPowerConduitobjects. Name itpowerConduits. Initialize it with anjava.util.ArrayList.List<PowerConduit>can hold any object whose class is a descendant ofPowerConduit!CrystalAmplifierobject (e.g., ID "CA-001", Crystal "Ruby").OrganicCapacitorobject (e.g., ID "OC-001", Biomatter "Luminous Moss").CrystalAmplifierobject (e.g., ID "CA-002", Crystal "Emerald").powerConduitslist.\n--- Activating All Conduits ---powerConduitslist using an enhanced for-loop. For eachconduitin the list:conduit.activateConduit();PowerConduitreference, the specific version forCrystalAmplifierorOrganicCapacitorwill be invoked. This is Dynamic Polymorphism!conduit.displayConduitStatus();(the concrete method from the abstract class).System.out.println();for better readability between conduit activations.\n--- Checking Specific Conduit Details ---powerConduitslist again.instanceofto check the actual type of eachconduit:CrystalAmplifier:conduittoCrystalAmplifier.setAmplificationLevel(10);method."Tuned CrystalAmplifier [conduitId]: New Amplification: [level], Crystal: [type]."OrganicCapacitor:conduittoOrganicCapacitor."OrganicCapacitor [conduitId] current energy: [energy stored] units."\n=== Citadel Systems Partially Restored. Well done, Apprentice! ===The Proof of Restoration (Expected Output Format):
Your
CitadelRestoration.javafile, when compiled and run, should produce console output that follows this pattern (exact IDs and some messages will match your implementation):(Note: Minor variations in constructor print order relative to each other are acceptable if all required prints for an object's creation are grouped).
Master Elara's Scoring Rubric (Total: 100 Points):
Chapter I: The Foundation Stone (30 Points)
PowerConduitClass:conduitId,isActive) with specified access modifiers andfinalkeyword (5 pts).CrystalAmplifierClass:PowerConduit(3 pts).crystalType,amplificationLevel) withprivateaccess (5 pts).super(), initializes own fields, print message) (5 pts).Chapter II: The Ethereal Blueprint (35 Points)
PowerConduitModifications:abstract(5 pts).activateConduit()declaredpublic abstractcorrectly (5 pts).displayConduitStatus()implemented correctly as a concrete method (5 pts).CrystalAmplifierModifications:activateConduit()correctly overridden (with@Override) and implemented as per logic (prints, sets active, sets amplification) (5 pts).OrganicCapacitorClass:PowerConduit(3 pts).privateaccess (3 pts).super(), initializes own fields, print message) (4 pts).activateConduit()correctly overridden (with@Override) and implemented as per logic (prints, sets active, updates energy) (5 pts).Chapter III: The Conductor's Baton (25 Points)
CitadelRestorationClass &mainmethod setup:mainmethod signature and class structure (3 pts).List<PowerConduit>(2 pts).activateConduit()polymorphically (5 pts).displayConduitStatus()(2 pts).instanceofand casting (5 pts).Overall Alchemical Purity (Best Practices & Conventions) (10 Points)
@paramand@returnwhere appropriate (4 pts).CitadelRestoration.java(1 pt).Final Words from Master Elara:
"The path of a Code Alchemist is one of continuous learning and refinement. This trial is but a stepping stone. Complete it, and the Citadel will breathe a little easier. Fail, and The Great Tangle tightens its grip. The choice, and the code, are yours. I await the Proof of Restoration."
Deliverable:
Your completed
CitadelRestoration.javafile. The output it produces when run will be your testament.Good luck, Apprentice! May your keystrokes be swift and your logic flawless.
Beta Was this translation helpful? Give feedback.
All reactions