I have an enum and on creating an instantion of a class, I want to create object of the class from Enum. Tbh I dont think so that I explained it properly so I will just show it.
public enum TypCiala{
GWIAZDA,
PLANETA,
KSIEZYC,
ASTEROIDA,
KOMETA
}
public Ciało(String nazwa, double okresOrbitowania, TypCiala typ) {
this.nazwa = nazwa;
this.okresOrbitowania = okresOrbitowania;
this.ksiezyce = new HashSet<>();
this.typ = typ;
}
while creating an instantion in Main method I want to create subclass of the typ(my enum) parameter
Ciało stack = new Ciało("Earth", 333, Ciało.TypCiala.PLANETA);
I have made the subclassed for Enum, but I have no idea how to implement them, so while creating the class there gonna be made subclass of this object
public class Planeta extends Ciało{
public Planeta(String nazwa, double okresOrbitowania, TypCiala typ) {
super(nazwa, okresOrbitowania, typ);
}
}
Related
New to Java. I'm trying to create a class to convert to JSON string to send as POST request using GSON. This class was created within a public class Called BertClient:
private class BertJsonRequest {
private Integer id;
private List<String> texts;
public BertJsonRequest(int x, String text) {
this.id = x;
this.texts = new ArrayList<>();
this.texts.add(text);
}
}
How I use that:
BertJsonRequest rawRequestBody = new BertJsonRequest(1, text);
Gson gsonToJson = new Gson();
String requestBody = gsonToJson.toJson(rawRequestBody);
For the line where I'm creating new BertJsonRequest My IDE tells me that BertClient.this cannot be referenced from a static content.
I wonder what that means.
Am I building the constructor correctly?
I think I'm not. I just want to be able to pass in a String so that constructor can create a List of String using that String.
Your class access modifier is set to private. Try setting the access modifier to public instead.
public class BertJsonRequest {
private Integer id;
private List<String> texts = new ArrayList<>();
public BertJsonRequest(int x, String text) {
id = x;
texts.add(text);
}
}
What I understood by reading your comments on other's answers was, that your BertClientRequest probably is an inner class.
In case it really is an inner class, and you try to call it in a static method of your containing class, it becomes apparent that you cannot instantiate your inner class as that inner class is not static.
public class BertClient {
private class BertClientRequest {
/* some code */
}
static void aStaticMethod() {
// ...
// Inner class BertClientRequest is unknown to your static method as it is not static,
// thus giving you a compile time error
BertClientRequest rawRequest = new BertClientRequest(1, text);
// ...
}
}
The fix would be in this case to change your inner class to static:
private static class BertClientRequest
I guess your BertJsonRequest is a inner class of BertClient. You can't instantiate BertJsonRequest outside of BertClient. You can make BertJsonRequest class static for this to work.
public class Player implements Comparable<Player> {
//Fields
private Name name;
private Rollable rollable;
//Constructors
public Player() {
name = new Name();
rollable = new Rollable();
}
public Player(Name name) {
this.name = name;
rollable = new Rollable();
}
public Player(Name name, Rollable rollable) {
this.name = name;
this.rollable = rollable;
}
Hello, for my constructors where i have put rollable = new Rollable(); I am getting an error which states that it Cannot instantiate the type rollable.
Below i have added the JUnit test and i will also add the code for the Rollable class
#Test
public void testDefaultConstructor() {
Player p = new Player();
assertEquals("Name field should be initialised with a default Name object ", new Name(), p.
getName());
assertTrue("Player's rollable field should be initialised with an. implementing instance of the Rollable interface", p.getRollable() instanceof Rollable);
}
#Test
public void testCustomConstructor1arg() {
Name n = new Name("Joe", "Bloggs");
Player p = new Player(n);
assertSame("Player's name field should be initialised with and return the same object received by the constructor", n, p.getName());
assertTrue("Player's rollable field should be initialised with an implementing instance of the Rollable interface", p.getRollable() instanceof Rollable);
}
Now below is the JUnit test for the default constructor whcih is also giving me the failure of Players rollable field should be initialised with an implementing instance of the Rollable interface, however, all of my other JUnit tests are passing.
#Test
public void testDefaultConstructor() {
Player p = new Player();
assertEquals("Name field should be initialised with a default Name object ", new Name(), p.getName());
assertTrue("Player's rollable field should be initialised with an implementing instance of the Rollable interface", p.getRollable() instanceof Rollable);
}
The code for my Rollable class is as below;
public interface Rollable {
public void roll();
public int getScore();
}
The methods for my rollable code are as below;
//Methods
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public Rollable getRollable() {
return rollable;
}
public void rollDice() {
rollable.roll();
}
public int getDiceScore() {
return rollable.getScore();
}
All help will be appreciated as i am struggling with the failures, thank you.
Your getRollable() method is:
public Rollable getRollable() {
return rollable;
}
So, if you call that from a constructor, for example:
public Player() {
name = new Name();
rollable = getRollable();
}
then rollable will be assigned the value of rollable, which is by default null.
As such, when you call getRollable() again in the test, you get back the value you assigned to the field - null - and by definition - null instanceof Rollable is false.
Instead, you need to create a new instance of Rollable, for example:
rollable = new Rollable();
(Don't know if it is directly instantiable. You've not provided the declaration of the Rollable class).
Your Rollable is an interface, and in Java you can only create instances of non-abstract classes.
So you need to write at least one class that implements Rollable. Of this class, you can create instances.
Why is that so?
Have a look at e.g. the Comparable interface (serving me as an analogon to your Rollable). Comparable denotes classes that support some kind of greater / equal / less than comparison, by requiring the class to have a method named compareTo(). If you were to instantiate a Comparable, what would you expect to be the result? A String, a Long, a Double or what? And the same applies to your Rollable.
An interface defines some requirements that implementing classes must fulfill, but they don't denote classes themselves, so you can't create (direct) instances of interfaces.
I have a following Java Code where enum data type is used to create instances of the base class as following:
Main Abstract Class:
public abstract class Element{
static enum elements{
quad8{Element create(){return new ElementQuad2D();}};
abstract Element create();
}
public static Element newElement (String name){
el=elements.valueOf(name);
return el.create();
}
public Element (String name, int nind, int nstress){
this.name = name;
/*Do Something Else*/
}
}
SubClass:
class ElementQuad2D extends Element{
public ElementQuad2D(){
super("quad8",8,4);
}
}
How to create enum type as above such that I can create the instance of different subclass based on element name like "quad8" in PYTHON?
This can be easily achieved with a dictionary from a string to the class. The use of subclasses doesn't play a role here:
class Element: pass
class ElementQuad2D(Element): pass
mapping = {'quad8': ElementQuad2D}
obj = mapping['quad8']()
print(obj)
# <__main__.ElementQuad2D object at 0x01D70BD0>
So let say I have such prototyping:
private static Hashtable<String, Furniture> map =
new Hashtable<String, Furniture>();
public My_product() {
loadCache();
}
public My_Product createProduct(String type, String name) {
Furniture cachedproduct = map.get(type);
return (Furniture) cachedproduct.clone();
}
private static void loadCache() {
Sub_product1 pr1 = new Sub_product1(null);
map.put("pr1", pr1);
Sub_product2 pr2 = new Sub_product2(null);
map.put("pr2", pr2);
}
So when I make an instance of an object, I don't know what value will be entered after cloning it (creating object using cloning). So I chosen null value for object instance. But when I clone it then I know what value needs to be assigned for that object. So how could I specify while cloning to put some value instead of null one from object instance?
As you can see in method createProduct method, there is argument called name. I would like that name to be used in cloned object, but how could I do that?
Can you use setter methods?
public My_Product createProduct(String type, String name) {
Furniture cachedproduct = map.get(type);
Furniture clonedProduct = (Furniture) cachedproduct.clone();
clonedProduct.setType(type);
clonedProduct.setName(name);
return clonedProduct;
}
However, I'm still not clear on the whole idea of this cloning of cached objects from the map. Is your product instantiation very expensive? What's the trick?
You cannot pass arguments through the Java built-in clone mechanism. You could provide a setter on the Furniture class to change the name after it has been cloned.
Note that cloning in Java is generally considered broken. It is a brittle way to create objects. Generally you are better of using the factory pattern, e.g. something like:
interface FurnitureBuilder {
Furniture build(String name);
}
class SubProduct1Builder implements FurnitureBuilder {
public Furniture build(String name) { return new SubProduct1(name); }
}
class MyFurnitureFactory {
private final Map<String, FurnitureBuilder> builderByType = ...
// initialization omitted
public Furniture create(String type, String name) {
return builderByType.get(type).build(name); // null check omitted!
}
}
If I have an Enum as a helper in a Java class, is there any way to refer to that Enum outside of the class it's helping?
Basically, what I have is this:
class Account extends MyClass {
HashMap<Property, String> property = new HashMap<Property, String>();
public Account() {
}
public enum Property {
USERID,
PASSWORD;
}
}
I want to be able to access the Property enum outside of the Account class.
The reason I want to do this is because this is a subclass of a another, and I want to be able to access the properties of a given subclass without refering to a unique enum name (ie: without refering to each one as, say, AccountProperty or ResearchProperty or TaskProperty... etc).
Your enum is public so you just can use Account.Property to access it from outside the Account class
EDIT :
If I got what you need, you'd like to do something like
Property p = Account.Property.PASSWORD;
Property p1 = Product.Property.CODE;
where Product is
public class Product extends MyClass{
HashMap<Account.Property, String> property = new HashMap<>();
public Product() {
}
public static enum Property {
CODE,
PRICE;
}
}
and you want to do this in your MyClass.
The problem is that both the two lines require an import and you can't import two classes with the same name, so the only solution is to do something like this
Account.Property p = Account.Property.PASSWORD;
Product.Property p1 = Product.Property.CODE;
I guess that you've got to deal with the instanceof to use the right Property enum for each class, as there's no way to extend an enum!
maybe something like the following (but this has no type checking):
import java.util.*;
abstract class MyClass {
Map<Object,String> properties=new HashMap<Object,String>();
}
class Account extends MyClass {
enum Property {
userid,password
}
//static Set<Property> keys=EnumSet.allOf(Property.class);
}
class Research extends MyClass {
enum Property {
red,green;
}
static Set<Property> keys=EnumSet.allOf(Property.class);
}
public class So10666881 {
public static void main(String[] args) {
Account account=new Account();
account.properties.put(Account.Property.userid,"user");
account.properties.put(Account.Property.password,"pass");
for(Account.Property property:Account.Property.values())
System.out.println(property+"="+account.properties.get(property));
}
}
Just declare the enum as a public top level enum class (in its own file)