Sequence Diagram into Java Codes : How to? - java

Goodday everyone. I'm actually having some trouble with these Sequence Diagrams. It says that " All animals live in their own cage depending on the race. " I really need a help with this simple diagram because i really dont know how to write it in my Java program. im sure its simple for most of yall. So please help me! here is the Diagram :
Zookeeper class / Mainclass :
package General;
import Zoo.Cage;
public class ZooKeeper {
public static void main(String[] args){
Cage cage1 = new Cage();
}
}
Cage class :
public class Cage {
private String type;
private ArrayList<Animal> cagedAnimals;
public Cage(String type){
this.type = type;
}
public Cage() {
}
public Animal selectAnimal(){
return null;
}
public void getCageType(){
}
public boolean addAnimal(Animal anAnimal){
return true;
}
public ArrayList<Animal> getCagedAnimals(){
ArrayList<Animal> i = new ArrayList<>();
return i;
}
public void addReptileEggs(ArrayList<Egg> reptileEggs){
}
}
Zoo class :
package Zoo;
import General.Animal;
import General.Egg;
import java.util.ArrayList;
import java.util.TreeSet`;
public class Zoo {
private final String name;
private TreeSet<Cage> cages;
/* private ArrayList<Cage> cages;*/
private String Zoo;
private static Zoo instance = new Zoo();
public Zoo() {
this.name = "AnimalK";
}
public static Zoo getInstance() {
if (instance == null) {
instance = new Zoo();
}
return instance;
}
}

You can see that everything happens in the constructor Cage():
public Cage() {
Zoo z = Zoo.getInstance("ICO41A");
boolean b = z.addCage(this);
}
Note that z could be a field if we need to use it later.
Class Zoo now: we've seen that getInstance has a String argument; I assume it's the name of the Zoo, and, instead of a single static instance, we can keep a static Map<String,Zoo>:
public class Zoo {
private static Map<String,Zoo> instances = new HashMap<>();
public static Zoo getInstance(String name) {
Zoo instance = instances.get(name);
if (instance == null) {
instance = new Zoo(name);
instances.put(name, instance);
}
return instance;
}
The name is passed to the constructor, and the Set cages is initialized (with an empty HashSet). I've used a HashSet instead of a TreeSet because Cage is not a Comparable:
private final String name;
private final Set<Cage> cages = new HashSet<>();
private Zoo(String name) {
this.name = name;
}
And finally, method addCage adds a Cage to the set:
public boolean addCage(Cage cage) {
return cages.add(cage);
}

Related

Static Objects are not getting stored in HashMap.!

I am trying to create a Map with key as a String and Value as a static class. But when I am printing the data, it only stores the last key-value pair. Can someone help me with this.
import java.util.HashMap;
import java.util.Map;
public class MapImplementation {
public static class Asset {
public static String assetName;
public static String assetType;
private void setAssetName(String name) {
Asset.assetName = name;
}
private void setAssetType(String type) {
Asset.assetType = type;
}
private String getAssetName() {
return assetName;
}
private String getAssetType() {
return assetType;
}
}
public static void main(String[] args) {
Map<String, Asset> map = new HashMap<>();
Asset asset1 = new Asset();
asset1.setAssetName("Vodafone");
asset1.setAssetType("STOCK");
map.put("Vodafone", asset1);
Asset asset2 = new Asset();
asset2.setAssetName("Google");
asset2.setAssetType("STOCK");
map.put("Google", asset2);
Asset asset3 = new Asset();
asset3.setAssetName("IBM");
asset3.setAssetType("BOND");
map.put("IBM", asset3);
for (String str : map.keySet()) {
Asset ast = map.get(str);
System.out.println(ast.getAssetName()+" "+ast.getAssetType());
}
}
}
The output I am getting is:
IBM BOND
IBM BOND
IBM BOND
Change:
public static String assetName;
public static String assetType;
to:
public String assetName;
public String assetType;
static fields are class level, not instance level - they are shared across all instances. Even though you are calling setters of different objects, the exact same 2 fields are being updated in those methods.

Easy access Object Getter with Java

Method 1: traditional getter/setter
Toyota class:
public class ToyotaCar implements Serializable {
private static final long serialVersionUID = 2011932556974180375L;
private int miles;
public void addMiles(int miles){
this.miles = miles;
}
public int getMiles(){
return miles;
}
}
Human class:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private ToyotaCar car;
public void setCar(ToyotaCar car){
this.car = car;
}
public int getCar(){
return car;
}
public void addCarMiles(int num){
getCar().addMiles(num);
}
}
Method 2: "other"
Toyota class: -same as above toyota class-
Additional containerHandler class:
public enum HumanContentsContainer {
CAR{
#Override public Object getContainer(){
return new ToyotaCar();
}
},
HOUSE;
public Object getContainer(){ //because cannot be static enum constant as every human has different items
return null;
}
}
Human class:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private HashMap<HumanContentsContainer, Object> contents;
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
contents.put(c, c.getContainer());
}
}
public HashMap<HumanContentsContainer, Object> getContents(){
return contents;
}
public void addCarMiles(int num){
//TODO how to replicate this: getCar().addMiles(num);???
}
//TODO i dont want to use the below method because whats the point of creating a whole container handler if im just going to use a traditional getter again?
//public ToyotaCar getCar(){
// return (ToyotaCar) contents.get(HumanContentsContainer.CAR);
// }
}
So how do I replicate the getCar().addMiles(x) method using a traditional getter without actually creating a getter?
Please note I also don't want to do this (below code): Because again, not worth it over a getter then:
public void addCarMiles(int num){
((ToytotaCar)contents.get(HumanContentsContainer.CAR).addMiles(num);
}
Looking for some easy kind of usage like:
human.getContentsThatIsIntanceOf(ToyotaCar).addMiles(1);
But don't know what getContentsThatIsInstanceOf would look like
I would go with:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private ToyotaCar car;
public void setCar(ToyotaCar car){
this.car = car;
}
public int getCar(){
return car;
}
public void addCarMiles(int num){
getCar().addMiles(num);
}
public Map<HumanContentsContainer, Object> getContents(){
Map<HumanContentsContainer, Object>map = new HashMap();
map.put(CAR,this.car );
//same for all the shoes and clothes and whatever the Human has
}
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
switch (c){
case CAR:{
this.car=c.getContainer();
}
}
//and so on
}
}
}
Edit
If you need to have a dynamic set of capabilities, I would suggest that you indeed keep the map of objects, and get rid of the ‘addCarMiles‘ method, as it implies that every human has a car.
I would implement public method on human ‘performCommand(CapabilityType, CapabilityCommand)‘ where the command will receive the capability and perform the operation on it. You may check out the Command Pattern tutorials.
Edit 2:
If all you want is to create a getter which will return dynamic type, you can use generics.
import java.io.Serializable;
import java.util.HashMap;
import java.util.NoSuchElementException;
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private HashMap<Class, Object> contents;
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
contents.put(c.getContainer().getClass(), c.getContainer());
}
}
public HashMap<Class, Object> getContents(){
return contents;
}
public <T> T getContentsThatIsIntanceOf(Class<T> type){
Object object = contents.get(type);
if (object==null){
throw new NoSuchElementException("No such element: "+type.getName());
}
return type.cast(object);
}
public void usageExample(){
this.getContentsThatIsIntanceOf(ToyotaCar.class).addMiles(10);
}
}

Java Interface containing an empty Enum

I'm trying to prepare an interface i want to implement for Datamodel-Classes.Therefor i want to use an enum inside the interface so i know i need to implement it later.
Example:
public interface MyModelInterface {
public enum Field;
public Object get(Field field);
public void set(Field field, Object value);
}
The expected implementation:
public class MyModel implements MyModelInterface {
public enum Field {
ID("id"),
Name1("Name1"),
Name2("Name2");
private String field;
private Field(String field) {
this.field = field;
}
}
public Object get(Field field) {
//...
}
public void set(Field field, Object value){
//...
}
public static void main(String[] args) {
MyModel myModel = new MyModel();
System.out.println(myModel.get(MyModel.Field.ID));
System.out.println(myModel.get(MyModel.Field.Name1));
}
}
Since I don't know which fields the model will contain until I implement it.
I did some research and figured that enum can't be extended, so i am aware of that.
is there any way to archive this or any kind of workaround?
i don't want to use String Parameters on the getter/setter Methods to avoid using wrong values.
Thanks in advance for any suggestion.
Update:
So this is what worked for me: Splitting the interface/class in three parts, including an abstract class:
Interface:
public interface MyModelInterface<E extends Enum<E>> {
public Object get(E field);
public void set(E field, Object value);
}
Abstract Class:
public abstract class MyAbstractModel<E extends Enum<E>> implements MyModelInterface<E>{
protected final EnumMap<E, Object> fields;
public MyAbstractModel(Class<E> enumKlazz) {
fields = new EnumMap<>(enumKlazz);
}
#Override
public Object get(E field) {
return fields.get(field);
}
#Override
public void set(E field, Object value) {
this.fields.put(field, value);
}
}
Class(where i actually archive my goal):
public class MyModel extends MyAbstractModel<MyModel.Field> {
public MyModel() {
super(MyModel.Field.class);
}
public enum Field {
ID("ID"),
Name1("NAME1"),
Name2("NAME2"),
Age("AGE"),
;
private final String field;
private Field(String field) {
this.field = field;
}
public String getName() {
return field;
}
}
public static void main(String[] args) {
MyModel myModel = new MyModel();
System.out.println(myModel.get(Field.Name1));
}
}
Interface fields are static and final implicitly.
What you could do is to have an interface method returning Enum<?>, and your classes implementing it.
For instance:
interface Foo {
public Enum<?> getEnum();
}
class Bar implements Foo {
enum Blah {
INSTANCE;
}
public Enum<?> getEnum() {
return Blah.INSTANCE;
}
}
Edit
Not completely sure I understand your question update, but here's a solution that will de-couple returning a specific enum instance from an enum, by means of two interfaces.
The example is self-contained in a Main class.
public class Main {
public static void main(String[] args) {
System.out.println(new Bar().getEnumField().name());
}
static interface IHasEnum {
public Enum<? extends IMyEnum> getEnumField();
}
static interface IMyEnum {
public Enum<? extends IMyEnum> getField();
}
static class Bar implements IHasEnum {
enum Blah implements IMyEnum {
DEFAULT_INSTANCE,
THE_FIELD;
public Enum<? extends IMyEnum> getField() {
return THE_FIELD;
}
}
public Enum<? extends IMyEnum> getEnumField() {
return Blah.DEFAULT_INSTANCE.getField();
}
}
}
Output
THE_FIELD
Note
The trick here is to add a "default" instance to the enum (DEFAULT_INSTANCE), so the getField method is an instance method, hence overriding the one declared in the IMyEnum interface.
Again, not entirely sure this addresses your issue.
What you are describing is an EnumMap<E, T> - which functions like an array, with that same get-
public class MyModelBase<E extends Enum<E>> {
private final Class<E> enumKlazz;
private final EnumMap<E, Object> fields;
public MyModelBase(Class<E> enumKlazz) {
this.enumKlazz = enumKlazz;
fields = new EnumMpa<>(enumKlazz);
}
public Object get(E field) {
return fields.get(field);
}
public void set(E field, Object value) {
fields.put(field, value);
}
}
enum UserField { id, surname, name, age };
MyModelBase<UserField> userModel = new MyModelBase<>(UserField.class);
userModel.set(UserField.surname, "X");
Because of type erasure the enum map needs the class. Above the enum class is also stored as field, as some static Enum methods need the enum class. For iterating, and so on.
Java generics will be the best solution.
Lets assume, you don't know the contents of the Field as mentioned.
Create a generic interface like this:
public interface MyModelInterface<T> {
public T get();
}
Then create a class Field like this:
public class Field {
private String id;
private String name1;
private String name2;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
}
and then your model class will look like
public class MyModel implements MyModelInterface<Field> {
#Override
public Field get() {
Field field = new Field();
field.setId("ID");
field.setName1("Name1");
field.setName2("Name2");
return field;
}
public static void main(String[] args) {
MyModel myModel = new MyModel();
System.out.println(myModel.get().getId());
System.out.println(myModel.get().getName1());
System.out.println(myModel.get().getName2());
}
}

How do I define or refer properties of model classes that is going to be used in the view

I want to make the situation where the developers have to define the properties of "model" classes to be shown in the views.
I've thought of using enumeration as the solution, but I don't think it is possible to define enumeration in a superclass (interface).
I'm sorry if my description is unclear. It's kinda hard to explain. I'll try explaining with a specific case.
Animal.java
public interface Animal {
public void eat();
}
Bird.java
public class Bird implements Animal
{
private String name;
private int age;
private Beak beak;
private Wings wings;
public Bird(String name, int age, Beak beak, Wings wings)
{
this.name = name;
this.age = age;
this.beak = beak;
this.wings = organ;
}
//getter setter..
#Override
public void eat() {
//eating
}
}
Snake.java
public class Snake implements Animal
{
private String name;
private int age;
private Fang fangs;
public Snake(String name, int age, Fang fangs)
{
this.name = name;
this.age = age;
this.fangs = fangs;
}
//getter setter..
#Override
public void eat() {
//eating
}
}
Zoo.java
public class Zoo
{
private ArrayList<Bird> birds = new ArrayList<Bird>();
private ArrayList<Snake> snakes = new ArrayList<Snake>();
private ArrayList<Object?> birdsShownFeatures = new ArrayList<Object?>();
private ArrayList<Object?> snakesShownFeatures = new ArrayList<Object?>();
public Zoo()
{
birds.add(new Bird("Vulture", 2, new CrookedBeak(), new WideWing()));
birds.add(new Bird("Whatever", 3, new WhateverBeak(), new WhateverWing()));
birds.add(new Bird("Wut", 4, new WutBeak(), new WutWing()));
snakes.add(new Snake("Cobra", 5, new TwinFang()));
snakes.add(new Snake("Whatever", 5, new WhateverFang()));
snakes.add(new Snake("Wut", 5, new WutFang()));
birdsShownFeatures.add(new Object?("name"));
birdsShownFeatures.add(new Object?("beak"));
birdsShownFeatures.add(new Object?("wings"));
snakesShownFeatures.add(new Object?("name"));
snakesShownFeatures.add(new Object?("fangs"));
}
public void showOff()
{
for(Bird bird:birds)
{
for(Object? object:birdsShownFeatures)
{
System.out.println("Bird: "+bird.unknownFunction(object));
}
}
for(Snake snake:snakes)
{
for(Object? object:snakesShownFeatures)
{
System.out.println("Snake: "+snake.unknownFunction(object));
}
}
}
}
I have to generalize the attributes of the subclasses of Animal (Object?). And I have to be able to define a function to retrieve that attribute (unknownFunction).
In other words, I want be able to make certain properties of animal's subclasses to be defined easily and are able to be processed accordingly.
Perfect (unreal?) Example:
public class Zoo {
private ArrayList<Bird> birds = new ArrayList<Bird>();
private ArrayList<Snake> snakes = new ArrayList<Snake>();
private ArrayList<Object> birdsShownFeatures = new ArrayList<Object>();
private ArrayList<Object> snakesShownFeatures = new ArrayList<Object>();
public Zoo()
{
birds.add(new Bird("Vulture", 2, new CrookedBeak(), new WideWing()));
birds.add(new Bird("Whatever", 3, new WhateverBeak(), new WhateverWing()));
birds.add(new Bird("Wut", 4, new WutBeak(), new WutWing()));
snakes.add(new Snake("Cobra", 5, new TwinFang()));
snakes.add(new Snake("Whatever", 5, new WhateverFang()));
snakes.add(new Snake("Wut", 5, new WutFang()));
birdsShownFeatures.add(Bird.NAME);
birdsShownFeatures.add(Bird.BEAK);
birdsShownFeatures.add(Bird.WINGS);
snakesShownFeatures.add(Snake.NAME);
snakesShownFeatures.add(Snake.FANGS);
}
public void showOff()
{
for(Bird bird:birds)
{
for(Object object:birdsShownFeatures)
{
System.out.println("Bird: "+bird.get(object));
}
}
for(Snake snake:snakes)
{
for(Object object:snakesShownFeatures)
{
System.out.println("Snake: "+snake.get(object));
}
}
}
}
enums can't work because I can't FORCE the developers to make specific enumeration that implements an interface everytime they make a class that implements Animal.
Both snakes and birds attributes have to be able to be generalized. But still defined. Making every attribute to implement a specific interface isn't a choice because it will be a pain in the a** to make all needed classes (including natives) implement an interface.
Sorry if it's too confusing. I don't know how to explain this case properly.
You could use reflection and generics. This answer to your problem but I thinks it's a bad choice.
Using your table example (see comments) I would use something like a generic Table<T> with a getRow() method returning a row (for Bird: "Vulture", 2, "CrookedBeak", "WideWing") and if the final developper wants a different kind of row, he can overrides your getRow to something else.
Another option would be to accept a Function<T, Row> in the table constructor (see google guava functions)
Quick & dirty sample generic and reflection code sample:
AbstractAnimal
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractAnimal<T extends Enum<T>> {
private List<T> selectedFields = new ArrayList<T>();
public AbstractAnimal(Class<T> clazz)
{
if (clazz != null) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers()) &&
Modifier.isPublic(field.getModifiers())) {
this.selectedFields.add(Enum.valueOf(clazz, field.getName()));
}
}
}
}
public abstract void eat();
public List<T> getSelectedFields()
{
return this.selectedFields;
}
public Object get(T name)
{
if (name == null) {
return null;
}
try {
final Class<?> clazz = this.getClass();
final Field declaredField = clazz.getDeclaredField(name.name().toLowerCase());
if (declaredField != null) {
declaredField.setAccessible(true);
return declaredField.get(this);
}
} catch (IllegalAccessException ex) {
// ignore
} catch (NoSuchFieldException e) {
// ignore
} catch (SecurityException e) {
// ignore
}
return null;
}
}
Bird
public class Bird extends AbstractAnimal<Bird.Fields> {
public static enum Fields {
NAME, AGE, BEAK, WINGS
}
private String name;
private int age;
private String beak;
private String wings;
public Bird(String name, int age, String beak, String wings)
{
super(Fields.class);
this.name = name;
this.age = age;
this.beak = beak;
this.wings = wings;
}
// getter setter..
#Override
public void eat()
{
// eating
}
}
Zoo
package com.foo;
import java.util.ArrayList;
public class Zoo {
private ArrayList<Bird> birds = new ArrayList<Bird>();
public Zoo()
{
birds.add(this.buildBird("Vulture", 2, "CrookedBeak", "WideWing"));
birds.add(this.buildBird("Whatever", 3, "WhateverBeak", "WhateverWing"));
birds.add(this.buildBird("Wut", 4, "WutBeak", "WutWing"));
}
public void showOff()
{
for(Bird bird:birds)
{
for (final Bird.Fields selectedField : bird.getSelectedFields()) {
System.out.println("bird: " + bird.get(selectedField));
}
}
}
private Bird buildBird(String name, int age, String beak, String wings)
{
Bird result = new Bird(name, age, beak, wings);
result.getSelectedFields().remove(Bird.Fields.AGE);
return result;
}
public static void main(final String[] args) {
Zoo z = new Zoo();
z.showOff();
}
}
Output
bird: Vulture
bird: CrookedBeak
bird: WideWing
bird: Whatever
bird: WhateverBeak
bird: WhateverWing
bird: Wut
bird: WutBeak
bird: WutWing

Is it possible to use Enum constants as templates for instantiable classes in Java?

Sorry if my question is a bit unclear; I'm finding it a little tough to find the wording. I spent several hours screwing around in Eclipse, cruising the JavaDoc, and Google, as well as SO. I learned a lot, but didn't find an answer.
What I'd like to be able to do is define an Enum, eg.:
public enum Animals {
Cow,
Chicken,
Sheep,
Horse;
}
and have each enum constant define an instantiable class that's not a local class. Would the following work? And if not, why, and what would?
In some file:
abstract public class Animal {
private String nameString;
public String getName() {
return nameString;
}
}
In another:
public enum Animals {
Cow ((new Animal() {
private boolean hasMilk;
{
nameString = "Cow";
hasMilk = false;
}
public boolean hasMilk() {
return hasMilk;
}
}).getClass()),
Chicken ((new Animal() {
private boolean hasFeathers;
{
nameString = "Chicken";
hasFeathers = true;
}
public boolean hasFeathers() {
return hasFeathers;
}
}).getClass()),
Sheep ((new Animal() {
private boolean isShorn;
{
nameString = "Cow";
isShorn = false;
}
public boolean isShorn() {
return isShorn;
}
public void Shear() {
isShorn = true;
}
}).getClass()),
Horse ((new Animal() {
{
nameString = "Cow";
}
}).getClass());
private Class<? extends Animal> animalClass;
private Animals(Class<? extends Animal> a) {
animalClass = a;
}
public Class<? extends Animal> getAnimalClass() {
return animalClass;
}
}
And then, in some other method of some other class, be able to do this:
Animal farmAnimal;
farmAnimal = Animals.Sheep.getAnimalClass().newInstance();
boolean shorn = farmAnimal.isShorn();
(The value of shorn being false at this point);
farmAnimal.shear();
shorn = farmAnimal.isShorn();
(shorn == true)
farmAnimal = Animals.Sheep.getAnimalClass().newInstance();
shorn = farmAnimal.isShorn();
(shorn == false)
Obviously, this isn't the best way to do what I've done here, but that's not the point. I know I can specify behaviour for enum constants, but that doesn't make them multiply-instantiable as distinct instances. I want to be able to create multiple instances (or copies) of various enum constants, with different instance variables (and different quantities/types of instance variables), with different accessor methods, which I can then do stuff to (alter instance variables) without modifying the enum constant.
I get that enum constants are designed to be immutable. That doesn't clash with my idea; I want each enum constant to represent an immutable definition of a mutable class.
You can do something like this:
public enum AnimalType {
COW {
#Override
public Animal createNew() {
return new Cow();
}
},
HORSE {
#Override
public Animal createNew() {
return new Horse();
}
};
public abstract Animal createNew();
}
public abstract class Animal {
private final AnimalType type;
private final String nameString;
public Animal(final AnimalType type, final String nameString) {
super();
this.type = type;
this.nameString = nameString;
}
public String getName() {
return nameString;
}
public AnimalType getType() {
return type;
}
}
public class Horse extends Animal {
public Horse() {
super(AnimalType.HORSE, "Horse");
}
}
public class Cow extends Animal {
private boolean milk;
public Cow() {
super(AnimalType.COW, "Cow");
}
public boolean hasMilk() {
return milk;
}
public void setMilk(final boolean milk) {
this.milk = milk;
}
}
#Test
public void testEnum() {
Cow cow = (Cow) AnimalType.COW.createNew();
Horse horse = (Horse) AnimalType.HORSE.createNew();
System.out.println("cow : " + cow.getType() + ", has milk: " + cow.hasMilk());
System.out.println("horse: " + horse.getType());
}

Categories