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>
Related
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);
}
}
I would like to store the class object of several classes that extend an abstract class in an array list. Please be aware, that I have to use an abstract class and no interface, because the class Country will contain more functionality.
The idea is to later access this class objects, create an object of them and call a method.
Question: How can I achieve this, because the following code produces errors.
import java.util.ArrayList;
public class Main
{
public static void main(String args[]) {
new Main();
}
public Main() {
// The idea is to add the class of all specific countries to the countries array
ArrayList<Class<Country>> countryclasses = new ArrayList<Class<Country>>();
// Doesn't work
countryclasses.add(England.class);
// Doesn't work
Class<Country> englandclass = England.class; // Error
countryclasses.add(englandclass);
// Doesn't work
England england = new England();
Class<Country> country = england.getClass().getSuperclass().getClass();
// Class<Country> country = england.getClass().getSuperclass().getClass();
countryclasses.add(country);
for(Class<Country> countryclass : countryclasses) {
// Create an object from the class
// Call the getName() method
}
}
public abstract class Country {
abstract String getName();
}
public class England extends Country {
public String getName() {
return "England";
}
}
}
If you really want to have a List<Class> instead of using a polymorphic collection of instances, you can use an upper-bounded wildcard to define classes that will be Country or extend it:
List<Class<? extends Country>> countryclasses = new ArrayList<Class<? extends Country>>();
Class<? extends Country> englandclass = England.class;
countryclasses.add(englandclass);
i need to declare a list which should accept only the parent class objects and it should not allow the sub class objects.
parent class:
public class ParentClass {
private String parentAttr;
public String getParentAttr() {
return parentAttr;
}
public void setParentAttr(String parentAttr) {
this.parentAttr = parentAttr;
}
}
Sub class:
public class SubClass1 extends ParentClass {
private String attr1;
public String getAttr1() {
return attr1;
}
public void setAttr1(String attr1) {
this.attr1 = attr1;
}
}
Main class:
public class MainClass {
public static void main(String[] args) {
ParentClass parentClass=new ParentClass();
SubClass1 subClass1 = new SubClass1();
List<ParentClass> list=new ArrayList<ParentClass>(); // modify this declaration such that it should accept only the parent class objs
list.add(parentClass);
list.add(subClass1); // this should not happen. only parent class objects should be added in the list
}
}
I tried using generics as well. but it is not working. is there any way to achieve this in java generics?
You can Implement the List interface and provide your own implementation for the List.add(int index, E element) method and check if the element is instanceof the parent Class and not an instanceof the child Class in your implementation.
You can also extend the ArrayList Class and Override all the methods that add elements to the ArrayList and check if the element is instanceof the parent Class and not an instanceof the child Class in your implementation and call the Super method for process of adding the element(s).
No. You just can't stop it. We can use every Child as a Parent. Every Child extends Parent and apparently it's a Parent as well.
For a particular program, I essentially have an abstract superclass with several different subclasses. However, I'm having trouble with field shadowing as illustrated below.
abstract class Super {
String name;
String getName() {
return name;
}
}
Now I create subclasses that each have their own "name".
class Sub extends Super {
name = "Subclass";
}
However, creating instances of the subclass, and then calling the inherited method getName() will yield null due to field shadowing.
Is there an easy way to avoid this problem, and to allow subclasses to each have a unique field that can be accessed by an inherited method?
Make the field visible in the child class and initialize it in the subclass constructor or in a subclass instance initializer.
You might try this mechanism (bonus left to reader, extend code to get the name of the class directly). The code use the Abstract classes constructor to set the name. You could also define a setName function in the Super class and use that.
Super class (abstract)
package stackShadow;
public abstract class Super {
String name;
public Super(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Shadow1 class first subclass
package stackShadow;
public class Shadow1 extends Super {
public Shadow1() {
super("Shadow1");
}
}
Shadow2 class second subclass
package stackShadow;
public class Shadow2 extends Super {
public Shadow2() {
super("Shadow2");
}
}
Test class to test getName
package stackShadow;
public class Test {
public static void main(String[] args) {
Shadow1 one = new Shadow1();
Shadow2 two = new Shadow2();
System.out.println("Name for one is: " + one.getName());
System.out.println("Name for two is: " + two.getName());
}
}
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)