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.
Related
I have multiple different classes Class1, Class2, Class3.
Each class has different variables and getters for them.
public class Class1 {
private String var1_1;
private String var1_2;
private String var1_3;
public String getVar1_1() { return var1_1;}
public String getVar1_2() { return var1_2;}
public String getVar1_3() { return var1_3;}
}
public class Class2 {
private String var2_1;
private String var2_2;
private String var2_3;
public String getVar2_1() { return var2_1;}
public String getVar2_2() { return var2_2;}
public String getVar2_3() { return var2_3;}
}
public class Class3 {
private String var3_1;
private String var3_2;
private String var3_3;
public String getVar3_1() { return var3_1;}
public String getVar3_2() { return var3_2;}
public String getVar3_3() { return var3_3;}
}
How can I write method which takes List of objects and getters(functions) as a method parameters?
For example:
List<Class1> list1 = //doesn't matter
List<Class2> list2 = //doesn't matter
List<Class3> list3 = //doesn't matter
generateRows(list1, Class1::getVar1_1, Class1::getVar1_3);
generateRows(list2, Class2::getVar2_1, Class2::getVar2_2, Class2::getVar2_3);
generateRows(list3, Class3::getVar3_1, Class3::getVar3_2);
Method
public void generateRows(List<T> list, /*???Something???*/... getters) {
for(T object: list) {
/*How to use getters to print?*/
/*System.out.println(obj.firtsGetter())*/
}
}
What I should write instead of ???Something???. Something like Function<T, String> or Consumer<T>? And how can I use getters in method?
You need to wrap the method calls in a Function. A Consumer, or another FunctionalInterface might do the trick as well, depending on your needs.
Then you need to have your method accept varargs of this function.
public static <T> void generateRows(List<T> list, Function<T, String>... getters) {
for (T object : list) {
for (Function<T, String> getter : getters) {
System.out.println(getter.apply(object));
}
}
}
Function will accept argument of type T and return a String. T can be anything - Class1, Class2, etc., as long you can return a string from this object - that means to have a getter method returning String in your case.
First you can defined a interface eg:
interface Get{
String getVar1();
String getVar2();
String getVar3();
}
Second All of classes implemente it:
class Class2 implements Get{
private String var2_1;
private String var2_2;
private String var2_3;
public String getVar1() { return var2_1;}
public String getVar2() { return var2_2;}
public String getVar3() { return var2_3;}
}
Third:
public void generateRows(List<T> list, Get ...getters) {
for(T object: list) {
/*How to use getters to print?*/
/*System.out.println(obj.firtsGetter())*/
}
}
I would like have one method declare two Strings and assign them values. Then have another method to read those values.
I have this structure:
public class ABC extends CDE implements EFG {
public void firstMethod(valueOne, valueTwo) {
class TestClass {
public String testValue = valueOne;
public String anotherValue = valueTwo;
}
}
public void readMethod() {
// HERE I WANT TO READ testValue AND ASSIGN IT A NEW VALUE
}
}
How can I do that?
And is there a better way?
Are you sure you need a class?
May be a simple field declaration will be enough:
public class ABC extends CDE implements EFG {
public String testValue;
public String anotherValue;
public void firstMethod(String valueOne, String valueTwo) {
// do whatever you wish with testValue and anotherValue
}
public void readMethod() {
// here you have access to both variables
}
}
Make the local class global and set/read values via instance:
public class ABC extends CDE implements EFG {
class TestClass {
public String testValue = valueOne;
public String anotherValue = valueTwo;
}
private testClassInstance = new TestClass()
public void firstMethod(valueOne, valueTwo) {
testClassInstance.testValue = valueOne
testClassInstance.anotherValue = valueTwo
}
public void readMethod() {
System.out.println(testClassInstance.valueOne)
System.out.println(testClassInstance.valueTwo)
}
}
All you want to do is to create a POJO that holds testValue and anotherValue and declare the class outside of your component class, e.g.:
class ExampleBean {
private String testValue;
private String anotherValue;
//getters and setters
}
Once done, you can hold the reference of that class into your component class and access the value, e.g.:
public class ABC extends CDE implements EFG {
ExampleBean exampleBean = new ExampleBEan();
public void firstMethod(valueOne, valueTwo) {
exampleBean.setValueOne(valueOne);
exampleBean.setAnotherValue(valueTwo);
}
public void readMethod() {
String value = exampleBean.getValueOne();
}
}
Maybe this will fit your criteria?
What you are currently asking for is impossible due to the scope of the inner class.
You could also initialize this private class instance in your constructor.
public class Sample {
class TestClass {
public String testValue;
public String anotherValue;
}
private TestClass localTest = new TestClass();
public void firstMethod(valueOne, valueTwo) {
localTest.testValue = valueOne;
localTest.anotherValue = valueTwo;
}
public void readMethod() {
localTest.testValue = "test1";
localTest.anotherValue = "anotherValue";
System.out.println(localTest.testValue);
}
}
You are declaring a class withing a method , which is not right
You need to understand what a class and a method really mean ( Google Java OOP ) :
1- You should create a class and declare the variables you want
2- make constructors for the default values
3- make setters to set (assign) these values
4- make getters to read those values
I have a list of utilities that derive from:
abstract public class BaseUtil implements Callable{
public String name;
public StreamWrapper data;
public void setData(StreamWrapper stream){ this.data = stream; }
private static Class me = BaseUtil.class;
private static Method[] availableUtilities = me.getDeclaredMethods();
public static Method[] getUtilities(){ return availableUtilities; }
}
I want to, at each node, be able to assign a utility to it, something like:
Initialize(String utilName){
activeUtility = utilName;
gk = new GateKeeper(BaseUtil.getUtilities() <something>);
}
public class GateKeeper {
GateKeeper(BaseUtil util) {
this.util = util;
}
private BaseUtil util;
But I'm unsure on how to get the specific utility class from just the String passed in. An example utility is:
public class WordLengthUtil extends BaseUtil {
private String name = "WordLength";
public Integer call() {
System.out.println(this.data);
return Integer.valueOf(this.data.length());
}
}
You can use reflection:
String name = "WordLength";
String className = hashMap.get(name);
Callable plugin = (Callable) Class.forName(className).newInstance();
use HashMap to store binding between className and string identifier
Probably a very basic java question.
I have an abstract class, simplifying it:
public abstract class A{
private String value = "A" ; // I want it undeclared, but set it for testing purpouse
public String getValue(){
return value ;
}
}
Then I have a class extending it:
public abstract class B{
private String value = "B" ;
}
So the problem I have is, when creating an instance of B through class A, and calling getValue(), it always return "A":
A b = new B();
b.getValue(); // returns "A"
How can I get B calling super method using his own properties without having to duplicate code? A it is currently too long, and it is extended to many different class that only differs by it properties values and all of them use the same methods that the super class has.
Thanks!
Edit:
Sorry, I wasn't so specific. I have a lot of properties, and some methods to deal with those properties. Extended class change those properties, but I want to use the super methods with the extended class instanced object without having to declare them twice. I'm working with servlets context atributtes if that helps.
Config.java
public abstract class Config {
private String someValue1 ;
...
private String someValuen ;
public void export(ServletContext cxt){
cxt.setAttribute("someValue1", someValue1);
...
cxt.setAttribute("someValuen", someValuen);
}
}
SomeConfig.java
public class SomeConfig {
private String someValue1 = "something" ;
...
private String someValuen = "something else" ;
}
SomeServlet.java
ServletContext cxt = getServletContext() ;
Config config = new SomeConfig();
config.export(cxt);
To make it clear, properties all have different names. I use them from jsp as: ${someValuen}
The reason why it doesn't work is that only methods can be overriden - variable members are hidden instead (if you print value from your B class, it will be "B").
For that specific example I would use a dedicated constructor (which I have made protected to prevent client classes from accessing it):
public abstract class A {
private final String value;
public A() { //for internal / testing use only
value = "A";
}
protected A(String value) {
this.value = value;
}
public String getValue(){
return value ;
}
}
Then B can simply call the relevant constructor:
public class B extends A {
public B() {
super("B");
}
}
EDIT
Example with a ConfigHolder:
public class ConfigHolder {
String value1;
String value2;
String value3;
public ConfigHolder value1(String value1) {
this.value1 = value1;
return this;
}
//same for other variables
}
Then in class A:
public abstract class A {
private final ConfigHolder config;
public A() {
this.config = new ConfigHolder()
.value1("value1")
.value2("value2");
}
protected A(ConfigHolder config) {
this.config = config;
}
public void export(ServletContext cxt){
cxt.setAttribute("someValue1", builder.value1);
...
cxt.setAttribute("someValuen", builder.valuen);
}
}
And in B:
public class B extends A {
public B() {
super(new ConfigBuilder()
.value1("value1InB")
.value2("value2InB"));
}
}
To do this: A b = new B(); B must be a subclass of A
Besides, an abstract class can not be instantiated, ie can not create abstract class objects. The compiler will produce an error if you try to.
public abstract class A{
private String value = "A" ;
public String getValue(){
return value ;
}
}
public class B extends A{
private String value ;
public B(){
value = "B";
}
}
Now you can do B notAbstractClass = new B();
And when doing notAbstractClass.getValue(); it must return "B"
I just figured out a simple way to do it with a constructor and changing the super class properties to protected (thanks to #assylias answer):
Config.java
public abstract class Config {
protected String someValue1 ;
...
protected String someValuen ;
public void export(ServletContext cxt){
cxt.setAttribute("someValue1", someValue1);
...
cxt.setAttribute("someValuen", someValuen);
}
}
SomeConfig.java
public class SomeConfig {
public SomeConfig(){
someValue1 = "something";
...
someValuen = "something else";
}
}
I have a primary class as below:
public class classB{
public classC getObject(String getstring){
return new classC(getstring);
}
}
The classC has a contructor:
public class classC{
String string;
public classC(String s){
this.string = s;
}
public methodC(int i){
<using the `string` variable here>
}
}
Now I've a classA which will be using the object created in classB(which is of course, an instance of classC).
public classA{
int a = 0.5;
<Get the object that was created in classB>.methodC(a);
}
This is needed as a variable is created on some actions from the user and stored in classB and this would be further used in classC's methods. Creating a new object will render my variable in classB set to null which isn't intended.
How can I achieve this?
Assume the Brand is a lightweight objects and Run is heavyweight then creating a field with the container for the lightweight objects and hiding it is a good idea.
But the Brand needs access the container it belongs to it could be done with the mapping but we are simply inject the Run to the Brand so it's better implement the Runable or annotate it with JSR330. And accessing the container through the Run in the normal way.
class MainClass {
public static void main(String[] args) {
Run r = new Run();
}
}
class Run {
private Container con1 = new Container();
public Run() {
Brand cola = new Brand("Coca Cola");
Brand pepsi = new Brand("Pepsi");
// Creates the container object "con1" and adds brands to container.
add(cola);
add(pepsi);
}
public void add(Brand b){
con1.addToList(b);
b.setRun(this);
}
public Container getContainer() {
return con1;
}
}
class Brand {
// In this class I have a method which needs to accsess the con1 object
// containing all the brands and I need to access the method
private String name;
private Run run;
public Brand(String name){
this.name = name;
}
public void brandMethod() {
if(getRun().getContainer().methodExample()) { // Error here. Can't find "con1".**
System.out.println("Method example returned true.");
}
}
public Run getRun() {
return run;
}
public void setRun(Run run) {
this.run = run;
}
}
class Container {
// This class is a container-list containing all brands brands
private ArrayList<Object> list = new ArrayList<Object>();
public boolean methodExample(){
return false;
}
public void addToList(Object o) {
list.add(o);
}
}
If you want to get the object created in classB a static field should do the job
public class classB {
public static objectCReference;
public classC getObject(String getstring){
objectCReference = new classC(getstring);
return objectCReference;
}
}
Then you can access the reference in A
public classA {
int a = 0.5;
if (classB.objectCReference != null) { // Make sure to null check
classB.objectCReference.methodC(a);
}
}
Also please follow the language conventions and start your class names with capital letters.