I have been give a jar file to use that has a static inner class inside of another static inner class:
package externalJarFile;
public class Job
{
public static class GlobalVars
{
private List<Job.GlobalVars.Variable> variables;
public List<Job.GlobalVars.Variable> getVariable()
{
if (this.variables == null) {
this.variables = new ArrayList<Job.GlobalVars.Variable>();
}
return this.variables;
}
public static class Variable
{
String name;
String value;
public String getName() { return name; }
public void setName( String name ) { this.name = name; }
public String getValue() { return value; }
public void setValue( String value) { this.value= value; }
}
}
}
The problem I'm having is that I need to populate the "Job.GlobalVars" list, but I can't figure out how to reference the "Variables" type. Whenever I add:
import externalJarFile.Job.GlobalVars.Variable;
I get a compilation error that the type "externalJarFile.Job.GlobalVars.Variable" cannot be referenced. How can I create a new "Variable" instance to add to the "GlobalVars.getVariable()" list?
Here's a snippet that I tried (but didn't work):
Job.GlobalVars vars = new Job.GlobalVars();
Job.GlobalVars.Variable v = new Job.GlobalVars.Variable();
[Edited for clarity]
[UPDATE]
Ok, this is kinda weird. If I take the code from the original project and directly import it into mine, I'm able to reference the inner-inner-class. However, when I reference it when it's packaged inside of a jar file, it fails. MTK...
You forgot a space:
Job.GlobalVars vars = new Job.GlobalVars();
^
This works fine for me:
Job.GlobalVars.Variable var = new Job.GlobalVars.Variable();
var.setName("MByD");
Class job:
package mypackage;
import java.util.ArrayList;
import java.util.List;
public class Job {
public static class GlobalVars
{
private List<Variable> variables;
public List<Variable> getVariable()
{
if (this.variables == null) {
this.variables = new ArrayList<Variable>();
}
return this.variables;
}
public static class Variable
{
String name;
String value;
public String getName() { return name; }
public void setName( String name ) { this.name = name; }
public String getValue() { return value; }
public void setValue( String value) { this.value= value; }
}
}
}
Other class using GlobalVars and Variable. Import works very good.
package mypackage;
import mypackage.Job.GlobalVars;
import mypackage.Job.GlobalVars.Variable;
public class RunIt {
public static void main(String[] args) {
GlobalVars vars = new GlobalVars();
Variable v = new Variable();
}
}
No need to import anything. You should be able to just refer to your inner class by its name, "Variable", from the "Job" class:
private List<Variable> variables;
public List<Variable> getVariable()
They way you had stated above is correct. You should check to ensure that the jar file is in your classpath as that would definitely cause the import to fail and subsequently all future declarations.
import mypackage.Job.GlobalVars.Variable;
...
Variable v = new Variable();
Related
My Package A has one java file with 2 classes. Login class which is public and LoginDetails class which cannot be public because it is in the same file. how to create a List of LoginDetails type from Package B.
package A;
public class Login {
private String name;
private String passWord;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
#Override
public String toString() {
return "Login [name=" + name + ", passWord=" + passWord + "]";
}
}
class LoginDetails{
public LoginDetails(int id, int geight) {
super();
this.id = id;
this.geight = geight;
}
private int id;
private int geight;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGeight() {
return geight;
}
public void setGeight(int geight) {
this.geight = geight;
}
public void hidden() {
System.out.println("From hidden");
}
public LoginDetails() {
}
}
package B;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
List<LoginDetails> l = new ArrayList<LoginDetails>();
}
}
A solution to your weird question which doesnt include changing neither of the Login nor LoginDetails classes would be by adding a second Public class called AUtils such like this:
AUtils/AFactory class
package A;
import java.util.ArrayList;
public class AUtils {
public static ArrayList<LoginDetails> generateList(){
return new ArrayList<LoginDetails>();
}
public static ArrayList<LoginDetails> generateListWithInitialSize(int x){
return new ArrayList<LoginDetails>(x);
}
public static LoginDetails generateAnObject(){
return new LoginDetails();
}
public static LoginDetails generateWithData(int id, int geight){
return new LoginDetails(id,geight);
}
}
And your Demo would look like this:
public class Demo {
public static void main(String[] args) {//plus you dont need To throw exception thus your program dont throw any!:)
List l = AUtils.generateList();
// List l = AUtils.generateListWithInitialSize(10);//will give you array list with initial size 10
l.add(AUtils.generateAnObject());//if you do so be aware that the objects would be created with 0 as id and eight.
// l.add(AUtils.generateWithData(3,3));
}
}
please be aware that this normally is not acceptable and considered as bad coding because its kinda turn around ;) so either you misunderstood the assignment or the one who wrote it is really a carrot.
happy coding.
You cannot do it directly without changing of the design or visibility of the classes.
If a class has no modifier (the default, also known as
package-private), it is visible only within its own package.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Trying to implement mathematical equation generation through recursively concatenating string returned by class containing same class as child nodes. Final equation contains repeated variables and I want to figure out how to end the recursion in this scenario.
I have a class1 which contains a Set/List of the same class1 objects. Also class1 contains Set/list of class2 and class3 objects. Now traversing through the parent class, I need to generate an expression from all the child and parent objects in a hierarchical manner. For eg: Exp1(class1) contains Exp2(class1), an operator(class3) and an attribute (class2). Now have to generate a long expression through the tree of objects such as class1,class2 are on the left and right sides of the equation and operator(op) in the middle.
public Map<String,String> generatecode(Map<String,String> Codes) {
String code = Codes.get("code");
String exit = Codes.get("exit");
String operator = "";
String operand1 = "";
String operand2 = "";
Set<Class2> attrs = getAttributes();
Set<Class1> exps = getExpressions();
if(attrs.size()>=2)
exit="1";
Iterator<Class2> itr = attrs.iterator();
while (itr.hasNext()) {
class2 attr=itr.next();
if(attr.getProperty("operand").equals("operand1")) {
operand1= attr.getName();
}
else if(attr.getProperty("operand").equals("operand2")) {
operand2= attr.getName();
}
}
if(!exit.equals("1") & exps!=null & !exps.isEmpty()) {
Iterator<Class1> itr = exps.iterator();
while (itr.hasNext()) {
Class1 exp=itr.next();
if(exp.getProperty("operand").equals("operand1")) {
Map<String,String> result=exp.generatecode(Map.of("code",code,"exit",exit));
exit=result.get("exit");
if(!operand1.contains(result.get("code")))
operand1+= result.get("code");
}
if(exp.getProperty("operand").equals("operand2")) {
Map<String,String> result=exp.generatecode(Map.of("code",code,"exit",exit));
exit=result.get("exit");
if(!operand2.contains(result.get("code")))
operand2+= result.get("code");
}
}
}
code += operand1+operator+operand2;
if(!exit.equals("1"))
code="";
return Map.of("code",code,"exit",exit);
}
Main class contains
Class1 aw_plus_w = new Class1();
Class3 waw_plus = new Class3("+");
aw_plus_w.addClass2(aw, Map.of("operand", "operand2"));
aw_plus_w.addClass2(w, Map.of("operand", "operand1"));
aw_plus_w.addOperator(waw_plus);
Class1 c_minus_w = new Class1();
Class3 cw_minus = new Class3("-");
c_minus_w.addClass2(c, Map.of("operand", "operand2"));
c_minus_w.addClass1(aw_plus_w, Map.of("operand", "operand1"));
c_minus_w.addOperator(cw_minus);
Class1 fr_div_size = new Class1();
Class3 fr_div = new Class3("/");
fr_div_size.addClass1(c_minus_w, Map.of("operand", "operand1"));
fr_div_size.addClass2(size, Map.of("operand", "operand2"));
fr_div_size.addOperator(fr_div);
String code="";
fr_div_size.generatecode(Map.of("code",code,"exit","0");
Expected result: ((aw+w)-c)/size
but
Actual result: ((w+aw-c-c)/(size()/(size)))
I tried for three days and could not find a way out. What is going wrong here? It will be grateful if anyone could point out the mistake
The updated sample code:
import java.util.HashSet;
import java.util.Set;
public class MyClass {
abstract class Node
{
public abstract String getCode();
// public abstract boolean isAttribute();
}
public class Attribute extends Node
{
private String name;
public Attribute(String name)
{
this.name=name;
}
public String getCode()
{
return name;
}
}
public class Expression extends Node
{
private String name;
private Set<Attribute> arg1 = new HashSet<Attribute>();
private Set<Expression> arg2 = new HashSet<Expression>();
private String op;
public Expression(Set<Attribute> arg1,Set<Expression> arg2, String op)
{
this.arg1=arg1;
this.arg2=arg2;
this.op=" "+op+" ";
}
public String getCode()
{
String result="";
// The correct code need to be written here
return result;
}
public Expression(String name)
{
this.name=name;
}
}
public static void main(String args[]) {
MyClass cl=new MyClass();
cl.run();
}
public void run(){
Attribute x=new Attribute("x");
Expression xpx=new Expression(Set.of(x,x),null,"+");
Expression xpxdx=new Expression(Set.of(x),Set.of(xpx),"/");
System.out.println(xpxdx.getCode());
}
}
I have not quite found the reason that you get the behaivor you are getting. I suspect it arises in the code you are not showing. (For example nothing in your code produces the "(" and ")" characters).
There is a likely bug though, in that at the top level you set exit="1", and you then pass that all the way down.
Your use of map to pass parameters makes your code much harder to read than it needs to be.
You should also look at polymorphism to carry the load for you.
If I understand your problem correctly the following is a simple implementation;
(Nesting of classes is because the online fiddle I was using did not allow multiple files, proper implementation should have separate classes in separate files.)
public class MyClass {
abstract class Expression
{
public abstract String getCode();
public abstract boolean isLiteral();
}
public class Literal extends Expression
{
private String name;
public Literal(String name)
{
this.name=name;
}
public String getCode()
{
return name;
}
public boolean isLiteral()
{
return true;
}
}
public class Binary extends Expression
{
private Expression arg1;
private Expression arg2;
private String op;
public Binary(Expression arg1,Expression arg2, String op)
{
this.arg1=arg1;
this.arg2=arg2;
this.op=" "+op+" ";
}
public String getCode()
{
String result="";
if(!arg1.isLiteral()) result+="("+arg1.getCode()+")";
else result+=arg1.getCode();
result+=op;
if(!arg2.isLiteral()) result+="("+arg2.getCode()+")";
else result+=arg2.getCode();
return result;
}
public boolean isLiteral()
{
return false;
}
}
public static void main(String args[]) {
MyClass cl=new MyClass();
cl.run();
}
public void run(){
Literal x=new Literal("x");
Expression xpx=new Binary(x,x,"+");
Expression xpxdx=new Binary(xpx,x,"/");
System.out.println(xpxdx.getCode());
}
}
This can be further improved by having an enumeration for the allowed operators.
Also it really should use the StringBuilder class rather than direct string concatenation.
Consider the following code for a read only interface pattern in Java:
package package2;
public interface AccountsReadOnly {
public String getValue();
}
package package1;
import package2.AccountsReadOnly;
class Accounts implements AccountsReadOnly {
private String name;
public Accounts() {
name = "unknown";
}
public String getValue() {
return name;
}
public void setValue(String name) {
this.name = name;
}
}
package package1;
public class Manager {
Accounts allAccess;
public Manager() {}
}
package package2;
public class Employee {
public AccountsReadOnly accountReadOnly;
public Employee() {}
}
public class Demo {
public static void main(String[] args) {
Manager m = new Manager();
Employee e = new Employee();
Accounts a = new Accounts();
m.allAccess = a;
m.allAccess.setValue("Andrew");
System.out.println(m.allAccess.getValue());
e.accountReadOnly = a;
System.out.println(e.accountReadOnly.getValue());
}
}
I can't understand this line as this is the first time for me to see this format:
m.allAccess.setValue("Andrew");
Is it possible to use instead of this line since they have the same reference?
m.setValue("Andrew");
Is m.allAccess a reference of the object?
Is it possible to use instead of this line since they have the same reference?
no, m.setValue("Andrew"); does not work, because the Manager-class has no function setValue
Is m.allAccess a reference of the object?
yes, allAccess references the Account-object which is set in this line: m.allAccess = a;
The getValue and setValue methods should really be named getNameand setName, because that what they do. setValueshould return a value, e.g. the account's balance.
Also nameis not read-only if you have a setter for it.
I am completely new to Java... :(
I need to pass a variable from a parent class to a child class, but I don't know how to do that.
The variable is located in a method in the parent class and I want to use it in one of the methods of the child class.
How is this done?
public class CSVData {
private static final String FILE_PATH="D:\\eclipse\\250.csv";
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
}
}
and then the other class
public class UserClassExperimental3 extends CSVData {
public static void userSignup() throws InterruptedException {
//some code here
String firstname= firstname1; //and here it doesnt work
}
}
Actually I think I succeeded doing that this way:
added the variable here:
public static void userSignup(String firstname1)
then used it here:
String firstname=firstname1;
System.out.println(firstname);
But now I can't pass it to the method that needs it.
The variable firstname1 is a local variable. You can't access it outside its scope - the method.
What you can do is pass a copy of the reference to your subclass.
Since you're calling a static method, the easiest way is to pass the reference as an argument to the method call:
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3.userSignup( firstName1 );
}
public class UserClassExperimental3 extends CSVData {
public static void userSignup( String firstNameArg ) throws InterruptedException {
//some code here
String firstname = firstnameArg; // Now it works
}
}
That said, since you're using inheritance, you might find it useful to use an instance method. Remove "static" from the method. In main(), construct an instance of the class, provide it the name, and call the method on the instance.
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3 instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
}
public class UserClassExperimental3 extends CSVData {
private String m_firstName;
public UserClassExperimental3( String firstName ) {
m_firstName = firstName;
}
public void userSignup() throws InterruptedException {
//some code here
String firstname = m_firstname; // Now it works
}
}
If you also add userSignup() to the CSVData class, you can refer to the specific subclass only on creation. This makes it easier to switch the implementation, and it makes it easier to write code that works regardless of which subclass you're using.
String firstname1 = array.get(2).get(1);
CSVData instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
public class Main {
public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setName("user");
user.setEmail("user#email.com");
user.save();
}
}
public class User extends Model {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import java.lang.reflect.Field;
public class Model {
public void save(){
for(Field field: Model.this.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
System.out.println(field.getName()+"="+field.get(Model.this));
} catch (Exception ex) {
ex.printStackTrace();
}
}
return;
}
}
I'm a bit confused with subclasses.
Here's my code:
public class MedHistory {
private String grafts;
private String allergies;
private String diseases;
private String surgeries;
private String medicalTreatment;
//Constructors (#2)
public MedHistory(String allergies, String diseases, String grafts,
String treatments, String surgeries) {
this.allergies=allergies;
this.diseases=diseases;
this.grafts=grafts;
this.medicalTreatment=treatments;
this.surgeries=surgeries;
}
public MedHistory() {
this.allergies="";
this.diseases="";
this.grafts="";
this.medicalTreatment="";
this.surgeries="";
}
//Getters
public String getGrafts() {
return grafts;
}
public String getAllergies() {
return allergies;
}
public String getDiseases() {
return diseases;
}
public String getSurgeries() {
return surgeries;
}
public String getMedicalTreatment() {
return medicalTreatment;
}
//Setters
public void setGrafts(String grafts) {
this.grafts = grafts;
}
public void setAllergies(String allergies) {
this.allergies = allergies;
}
public void setDiseases(String diseases) {
this.diseases = diseases;
}
public void setSurgeries(String surgeries) {
this.surgeries = surgeries;
}
public void setMedicalTreatment(String medicalTreatment) {
this.medicalTreatment = medicalTreatment;
}
public class FemMedHistory extends MedHistory {
private List<Birth> births = new ArrayList<Birth>();
//Constructors (#2)
public FemMedHistory(String allergies, String diseases, String grafts,String treatments, String surgeries, List<Birth> birthlist) {
super(allergies,allergies,grafts,treatments,surgeries);
this.births=birthlist;
}
public FemMedHistory() {
super();
this.births=null;
}
//Getter
public List<Birth> getBirths() {
return this.births;
}
//Setter
public void setBirths(List<Birth> list) {
this.births=list;
}
}
}
When I try to create an new FemMedHistory object like this:
List<Birth> list = new ArrayList<Birth>();
list.add(new Birth(new GregorianCalendar(2011,4,10),"kaisariki",4));
FemMedHistory female = new FemMedHistory("allergia2","astheneia2","emvolia2","farmekeutiki agwgi2", "xeirourgeia2", list);
I get the error:
No enclosing instance of type MedHistory is accessible. Must qualify
the allocation with an enclosing instance of type MedHistory (e.g.
x.new A() where x is an instance of MedHistory).
So, which is the right way to use a subclass?
When you declare a nested class it only available through the Outer class.
To access it outside, you will need to either make the FemMedHistory class static.
public static class FemMedHistory extends MedHistory {...}
access it through the MedHistory class
MedHistory.FemMedHistory myMedHistory = ...
or declare it in it's own Java file.
You have declared your subclass as an inner class, which means that you can't create an instance of it without first creating an instance of the containing class.
The most common way to solve this is to declare it as a separate class, which would get rid of your error.
Long story short: cut all the FemMedHistory code and paste it into FemMedHistory.java. The way it is now you have involved Java concepts which you have not yet mastered. Also, that class really does belong in a separate file.