0% found this document useful (0 votes)
4 views10 pages

Week 5 - S5 - Core OOP - Encapsulation - Lab Problem

The document contains Java code for a virtual pet system with classes representing virtual pets, their species, and various pet types like dragons and robots. It also includes a kingdom configuration system with classes for magical structures, wizards, castles, libraries, and dragon lairs. The code emphasizes object-oriented principles with encapsulation, constructors, and methods for interaction and state management.

Uploaded by

Puneet Narang
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Week 5 - S5 - Core OOP - Encapsulation - Lab Problem

The document contains Java code for a virtual pet system with classes representing virtual pets, their species, and various pet types like dragons and robots. It also includes a kingdom configuration system with classes for magical structures, wizards, castles, libraries, and dragon lairs. The code emphasizes object-oriented principles with encapsulation, constructors, and methods for interaction and state management.

Uploaded by

Puneet Narang
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1) Program code:

package [Link];

class VirtualPet {
private final String petId;
private final PetSpecies species;
private final long birthTimestamp;
private String petName;
private int age;
private int happiness;
private int health;
protected static final String[] DEFAULT_EVOLUTION_STAGES
= {"Egg", "Baby", "Teen", "Adult"};
static final int MAX_HAPPINESS = 100;
static final int MAX_HEALTH = 100;
public static final String PET_SYSTEM_VERSION = "2.0";
public VirtualPet() {
this(generatePetId(), "Default", new PetSpecies("Standard",
DEFAULT_EVOLUTION_STAGES, 10, "Home"),
[Link](), 0, 50, 50);
}
public VirtualPet(String petName) {
this(generatePetId(), petName, new PetSpecies("Standard",
DEFAULT_EVOLUTION_STAGES, 10, "Home"),
[Link](), 0, 50, 50);
}
public VirtualPet(String petName, PetSpecies species) {
this(generatePetId(), petName, species,
[Link](), 0, 50, 50);
}
public VirtualPet(String petId, String petName, PetSpecies
species, long birthTimestamp, int age, int happiness, int health) {
if (species == null || petId == null || petName == null) throw
new IllegalArgumentException();
[Link] = petId;
[Link] = species;
[Link] = birthTimestamp;
setPetName(petName);
setAge(age);
setHappiness(happiness);
setHealth(health);
}
private static String generatePetId() { return
[Link]([Link]()); }
private void validateStat(int stat) { if(stat < 0 || stat > 100) throw
new IllegalArgumentException(); }
public String getPetId() { return petId; }
public PetSpecies getSpecies() { return species; }
public long getBirthTimestamp() { return birthTimestamp; }
public String getPetName() { return petName; }
public void setPetName(String petName) { if(petName == null)
throw new IllegalArgumentException(); [Link] = petName; }
public int getAge() { return age; }
public void setAge(int age) { if(age < 0) throw new
IllegalArgumentException(); [Link] = age; }
public int getHappiness() { return happiness; }
public void setHappiness(int happiness) { validateStat(happiness);
[Link] = happiness; }
public int getHealth() { return health; }
public void setHealth(int health) { validateStat(health); [Link]
= health; }
public void feedPet(String foodType) {
modifyHealth(calculateFoodBonus(foodType));
[Link](petName + " was fed with " + foodType + " and health
increased!");
}
public void playWithPet(String gameType) {
modifyHappiness(calculateGameEffect(gameType));
[Link](petName + " played " + gameType + " and became
happier!");
}
protected int calculateFoodBonus(String foodType) { return 10; }
protected int calculateGameEffect(String gameType) { return 15;
}
private void modifyHappiness(int delta) {
setHappiness([Link](MAX_HAPPINESS, happiness + delta)); }
private void modifyHealth(int delta) {
setHealth([Link](MAX_HEALTH, health + delta)); }
String getInternalState() { return toString(); }
public String toString() {
return "[ID=" + petId + ", Name=" + petName + ", Species=" +
species + ", Age=" + age +
", Happiness=" + happiness + ", Health=" + health + "]";
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VirtualPet)) return false;
VirtualPet vp = (VirtualPet) o;
return [Link]([Link]);
}
public int hashCode() { return [Link](); }
}
final class PetSpecies {
private final String speciesName;
private final String[] evolutionStages;
private final int maxLifespan;
private final String habitat;
public PetSpecies(String speciesName, String[] evolutionStages,
int maxLifespan, String habitat) {
if(speciesName == null || evolutionStages == null ||
[Link] == 0 || maxLifespan <= 0 || habitat ==
null)
throw new IllegalArgumentException();
[Link] = speciesName;
[Link] = [Link]();
[Link] = maxLifespan;
[Link] = habitat;
}
public String getSpeciesName() { return speciesName; }
public String[] getEvolutionStages() { return
[Link](); }
public int getMaxLifespan() { return maxLifespan; }
public String getHabitat() { return habitat; }
public String toString() { return speciesName; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PetSpecies)) return false;
PetSpecies ps = (PetSpecies) o;
return [Link]([Link]);
}
public int hashCode() { return [Link](); }
}
class DragonPet {
private final String dragonType;
private final String breathWeapon;
private VirtualPet base;
public DragonPet(String dragonType, String breathWeapon,
VirtualPet base) {
if(dragonType == null || breathWeapon == null) throw new
IllegalArgumentException();
[Link] = dragonType;
[Link] = breathWeapon;
[Link] = base;
}
public String getDragonType() { return dragonType; }
public String getBreathWeapon() { return breathWeapon; }
public VirtualPet getBase() { return base; }
public String toString() { return "[DragonType=" + dragonType +
", BreathWeapon=" + breathWeapon + "]"; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DragonPet)) return false;
DragonPet dp = (DragonPet) o;
return [Link]([Link]) &&
[Link]([Link]);
}
public int hashCode() { return [Link]() +
[Link](); }
}
class RobotPet {
private boolean needsCharging;
private int batteryLevel;
private VirtualPet base;
public RobotPet(boolean needsCharging, int batteryLevel,
VirtualPet base) {
[Link] = needsCharging;
[Link] = batteryLevel;
[Link] = base;
}
public boolean isNeedsCharging() { return needsCharging; }
public void setNeedsCharging(boolean v) { needsCharging = v; }
public int getBatteryLevel() { return batteryLevel; }
public void setBatteryLevel(int v) { batteryLevel = v; }
public VirtualPet getBase() { return base; }
public String toString() { return "[NeedsCharging=" +
needsCharging + ", Battery=" + batteryLevel + "%]"; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RobotPet)) return false;
RobotPet rp = (RobotPet) o;
return needsCharging == [Link] && batteryLevel
== [Link];
}
public int hashCode() { return [Link](needsCharging)
+ batteryLevel; }
}
// Entry point
public class Main {
public static void main(String[] args) {
PetSpecies dragonSpecies = new PetSpecies("Dragon", new String[]{"Egg",
"Wyrmling", "Young", "Adult", "Ancient"}, 1000,"Mountains");
VirtualPet pet = new VirtualPet("Smaug", dragonSpecies);
DragonPet dragon = new DragonPet("Fire Dragon", "Flame Breath", pet);
RobotPet robo = new RobotPet(true, 80, new VirtualPet("RoboPet"));
[Link]("=== Virtual Pet System v" +
VirtualPet.PET_SYSTEM_VERSION + " ===");
[Link]("Created Virtual Pet: " + pet);
[Link]("Created Dragon Pet: " + dragon + " linked to " +
[Link]().getPetName());
[Link]("Created Robot Pet: " + robo + " linked to " +
[Link]().getPetName());
[Link]("\n--- Interactions ---");
[Link]("Meat");
[Link]("Treasure Hunt");
[Link]("\nUpdated Pet State: " + pet);
[Link]("Robot battery level: " + [Link]() +
"%");
}
}

Output:

2) Program code:
package [Link];

import [Link].*;
class KingdomConfig {
private final String kingdomName;
private final int foundingYear;
private final String[] allowedStructureTypes;
private final Map<String, Integer> resourceLimits;
public KingdomConfig(String kingdomName, int foundingYear,
String[] allowedStructureTypes, Map<String, Integer>
resourceLimits) {
if (kingdomName == null || allowedStructureTypes == null ||
[Link] == 0 || resourceLimits == null)
throw
new IllegalArgumentException();
[Link] = kingdomName;
[Link] = foundingYear;
[Link] = [Link]();
[Link] = new HashMap<>(resourceLimits);
}
public String getKingdomName() { return kingdomName; }
public int getFoundingYear() { return foundingYear; }
public String[] getAllowedStructureTypes() { return
[Link](); }
public Map<String, Integer> getResourceLimits() { return new
HashMap<>(resourceLimits); }
public static KingdomConfig createDefaultKingdom() { return
new KingdomConfig("Default", 1000, new String[] {"Tower",
"Castle", "Library", "Lair"}, new HashMap<>()); }
public static KingdomConfig createFromTemplate(String type) {
return createDefaultKingdom(); }
public String toString() { return kingdomName; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof KingdomConfig)) return false;
KingdomConfig kc = (KingdomConfig) o;
return [Link]([Link]);
}
public int hashCode() { return [Link](); }
}
class MagicalStructure {
private final String structureId;
private final long constructionTimestamp;
private final String structureName;
private final String location;
private int magicPower;
private boolean isActive;
private String currentMaintainer;
static final int MIN_MAGIC_POWER = 0;
static final int MAX_MAGIC_POWER = 1000;
public static final String MAGIC_SYSTEM_VERSION = "3.0";
public MagicalStructure(String name, String location) {
this(name, location, 0, false);
}
public MagicalStructure(String name, String location, int power) {
this(name, location, power, false);
}
public MagicalStructure(String name, String location, int power,
boolean active) {
if (name == null || location == null || power <
MIN_MAGIC_POWER || power > MAX_MAGIC_POWER) throw
new IllegalArgumentException();
[Link] = [Link]([Link]());
[Link] = name;
[Link] = location;
[Link] = power;
[Link] = active;
[Link] = [Link]();
}
public String getStructureId() { return structureId; }
public long getConstructionTimestamp() { return
constructionTimestamp; }
public String getStructureName() { return structureName; }
public String getLocation() { return location; }
public int getMagicPower() { return magicPower; }
public void setMagicPower(int p) { if (p <
MIN_MAGIC_POWER || p > MAX_MAGIC_POWER) throw new
IllegalArgumentException(); magicPower = p; }
public boolean isActive() { return isActive; }
public void setActive(boolean v) { isActive = v; }
public String getCurrentMaintainer() { return currentMaintainer; }
public void setCurrentMaintainer(String v) { currentMaintainer =
v; }
public String toString() { return structureName; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MagicalStructure)) return false;
MagicalStructure ms = (MagicalStructure) o;
return [Link]([Link]);
}
public int hashCode() { return [Link](); }
}
class WizardTower {
private final int maxSpellCapacity;
private List<String> knownSpells;
private String currentWizard;
public WizardTower() { this(10, new ArrayList<>(), ""); }
public WizardTower(int maxSpellCapacity, List<String>
knownSpells, String currentWizard) {
[Link] = maxSpellCapacity;
[Link] = new ArrayList<>(knownSpells);
[Link] = currentWizard;
}
public int getMaxSpellCapacity() { return maxSpellCapacity; }
public List<String> getKnownSpells() { return new
ArrayList<>(knownSpells); }
public void setKnownSpells(List<String> v) { knownSpells =
new ArrayList<>(v); }
public String getCurrentWizard() { return currentWizard; }
public void setCurrentWizard(String v) { currentWizard = v; }
public String toString() { return currentWizard; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof WizardTower)) return false;
WizardTower wt = (WizardTower) o;
return maxSpellCapacity == [Link];
}
public int hashCode() { return maxSpellCapacity; }
}
class EnchantedCastle {
private final String castleType;
private int defenseRating;
private boolean hasDrawbridge;
public EnchantedCastle() { this("Fort", 50, false); }
public EnchantedCastle(String type, int rating, boolean
drawbridge) {
castleType = type;
defenseRating = rating;
hasDrawbridge = drawbridge;
}
public String getCastleType() { return castleType; }
public int getDefenseRating() { return defenseRating; }
public void setDefenseRating(int v) { defenseRating = v; }
public boolean isHasDrawbridge() { return hasDrawbridge; }
public void setHasDrawbridge(boolean v) { hasDrawbridge = v; }
public String toString() { return castleType; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EnchantedCastle)) return false;
EnchantedCastle ec = (EnchantedCastle) o;
return [Link]([Link]);
}
public int hashCode() { return [Link](); }
}
class MysticLibrary {
private final Map<String, String> bookCollection;
private int knowledgeLevel;
public MysticLibrary() { this(new HashMap<>(), 10); }
public MysticLibrary(Map<String, String> books, int level) {
bookCollection = new HashMap<>(books);
knowledgeLevel = level;
}
public Map<String, String> getBookCollection() { return new
HashMap<>(bookCollection); }
public int getKnowledgeLevel() { return knowledgeLevel; }
public void setKnowledgeLevel(int v) { knowledgeLevel = v; }
public String toString() { return "" + knowledgeLevel; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MysticLibrary)) return false;
MysticLibrary ml = (MysticLibrary) o;
return knowledgeLevel == [Link];
}
public int hashCode() { return knowledgeLevel; }
}
class DragonLair {
private final String dragonType;
private final long treasureValue;
private int territorialRadius;
public DragonLair(String type, long treasure, int radius) {
dragonType = type;
treasureValue = treasure;
territorialRadius = radius;
}
public String getDragonType() { return dragonType; }
public long getTreasureValue() { return treasureValue; }
public int getTerritorialRadius() { return territorialRadius; }
public void setTerritorialRadius(int v) { territorialRadius = v; }
public String toString() { return dragonType; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DragonLair)) return false;
DragonLair dl = (DragonLair) o;
return [Link]([Link]);
}
public int hashCode() { return [Link](); }
}
class KingdomManager {
private final List<Object> structures;
private final KingdomConfig config;
public KingdomManager(List<Object> structures,
KingdomConfig config) { [Link] = new
ArrayList<>(structures); [Link] = config; }
public static boolean canStructuresInteract(Object s1, Object s2) {
return (s1 instanceof MagicalStructure && s2 instanceof
MagicalStructure) ||
(s1 instanceof WizardTower && s2 instanceof
EnchantedCastle);
}
public static String performMagicBattle(Object attacker, Object
defender) {
return "Battle performed between " + attacker + " and " +
defender;
}
public static int calculateKingdomPower(Object[] structures) {
int sum = 0;
for(Object s: structures) {
if(s instanceof MagicalStructure) sum +=
((MagicalStructure)s).getMagicPower();
}
return sum;
}
private String determineStructureCategory(Object structure) {
if(structure instanceof MagicalStructure) return
"MagicalStructure";
if(structure instanceof WizardTower) return "WizardTower";
if(structure instanceof EnchantedCastle) return
"EnchantedCastle";
if(structure instanceof MysticLibrary) return "MysticLibrary";
if(structure instanceof DragonLair) return "DragonLair";
return "";
}
}
public class MainClass {
public static void main(String[] args) {
KingdomConfig config =
[Link]();
[Link]("Kingdom: " + [Link]() +
" Founded: " + [Link]());
MagicalStructure tower = new MagicalStructure("Magic Tower", "North",
200, true);
WizardTower wizardTower = new WizardTower(20,
[Link]("Fireball","Teleport"), "Merlin");
EnchantedCastle castle = new EnchantedCastle("Royal", 80, true);
MysticLibrary library = new MysticLibrary([Link]("Book of
Spells","Ancient magic"), 50);
DragonLair lair = new DragonLair("Fire Dragon", 1000000, 30);
[Link]("Magical Structure: " + [Link]() + "
Power=" + [Link]());
[Link]("Wizard Tower Wizard: " +
[Link]());
[Link]("Enchanted Castle: " + [Link]() + "
Defense=" + [Link]());
[Link]("Mystic Library Knowledge Level: " +
[Link]());
[Link]("Dragon Lair Type: " + [Link]() + "
Treasure=" + [Link]());
[Link]("Can WizardTower and Castle interact? " +
[Link](wizardTower, castle));
[Link]("Magic Battle: " +
[Link](tower, castle));
Object[] allStructures = {tower, wizardTower, castle, library, lair};
[Link]("Total Kingdom Power: " +
[Link](allStructures));
}
}

Output:

You might also like