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.
Related
I am trying to re-build an OOP approach to mobile verification at the developers discretion. The concept I come up with is to allow for interfaces to manipulate the class. If the class implements the interface, then the verify method will be executed.
The problem I am facing, because I am only used to programming in less strongly-typed languages (PHP) is how to get a protected variable from a class extending the current class.
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
This line of code is now giving me an error
_mobileNumber cannot be resolved or is not a field
Here is my full code and here is an example I wrote of the same concept in PHP which I am trying to implement in Java.
import java.util.ArrayList;
interface Verification
{
public void initVerification();
}
class AreaCode
{
private int _code;
private String _country;
public AreaCode(int code, String country)
{
this._code = code;
this._country = country;
}
public int getAreaCode() { return this._code; }
public String getAreaCountry() { return this._country; }
}
class VerificationHandler
{
private ArrayList<AreaCode> _areaCodes = new ArrayList<AreaCode>() {{
this.add(new AreaCode(44, "UNITED KINGDOM"));
this.add(new AreaCode(91, "INDIA"));
}};
public void initVerification()
{
if(this instanceof Verification) {
this.verify();
}
}
protected void verify()
{
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
}
}
class Main extends VerificationHandler implements Verification {
protected String _mobileNumber = "+447435217761";
}
public class Hack1337 { public static void main(String[] args) { new Main(); } }
How can I retrieve a variable in a class extending another, ie:
class A { public String getB() { return this.b; } }
class B extends A { protected String b = 'A should get this'; }
B b = new B().getB();
Only instances of class B, or sub-classes of B can access the b instance variable directly (unless you cast A to B within the body of the A class, which is bad practice).
You can give class A read-only access to that value by overriding getB():
class B extends A
{
protected String b = 'A should get this';
#Override
public String getB() {
return this.b;
}
}
and you may also want to make the getB() method abstract in class A (which means making class A abstract):
abstract class A
{
public abstract String getB();
}
This would only make sense if different sub-classes of A are expected to return different things in getB(). Otherwise, you may as well move the b variable to the base class A.
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'm coding a program to manage reservations and for that I have a class Reservation and a class ReservationFactory.
Im trying to create a new reservation using the factory but im getting this problem:
"Cannot make a static reference to the non-static method getReservation() from the type ReservationFactory"
public class Reservation {
public Reservation() {
ReservationFactory.getReservation();
}
public Reservation(int code) {
this.code = code;
}
}
class ReservaFactory {
public Reservation getReservation() {
Reservation r = new Reservation(this.getCode());
return r;
}
public int getCode() {
return this.code;
}
}
Any ideas how to solve it? Thanks
The main (if not whole) point about factory methods/classes is to reduce the need for or eliminate direct constructor calls.
What you're trying to do is technically impossible. From a constructor, a call to a different method returning the same type as the one being constructed can only result in 2 objects, or an expected exception, or a stack overflow error (I'm probably missing some outcomes here, but I can't imagine that any would be desirable).
Alternative patterns using a factory include:
public class Reservation {
//Hide the constructor
private Reservation() {
}
private Reservation(int code) {
this.code = code;
}
//Use a factory method in the same class
public static Reservation instance(int code) {
Reservation r = new Reservation();
r.code = code;
return r;
}
//A builder class, which could also be declared externally
public static class Builder {
//optional parameter
private int code;
public Reservation getReservation() {
return new Reservation(this.code());
}
//A "setter" enabling fluent API
public Builder code(int code) {
this.code = code;
return this;
}
}
}
The factory method is decided runtime which object is going to be instantiated.
Lets assume you have abstract class as Reservation.
public abstract class Reservation {
public Reservation() {
ReservationFactory.getReservation();
}
public Reservation(int code) {
this.code = code;
}
abstract void bookTicket();
}
You may have two classes such as RailwayReservation and AirLineReservation. Which extends base class Reservation.
public class RailwayReservation extends Reservation {
public RailwayReservation(int code){
super(code);
}
void bookTicket(){
System.out.println("Railaway Reservation call");
}
}
public class AirlineReservation extends Reservation {
public AirlineReservation(int code){
super(code);
}
void bookTicket(){
System.out.println("Railaway Reservation call");
}
}
Then for instantiating an object of Reservation class ReservationFactory you are creating. ReservationFactory will give you a Reservation's class object on the bases of your input.
Let's take a choice, If you call getReservation with id = 1 then it will return RailwayReservation's instance and id=2 then it will return AirlineReservation's instance.
class ReservaFactory {
public static Reservation getReservation(int id, int code) {
Reservation r = null;
if(id==1){
r = new RailwayReservation();
}else if(id==2){
r = new AirlineReservation();
}
return r;
}
}
We can call it by using following method.
public static void main(String[] args){
Reservervaion r1 = ReservationFactory.getReservation(1,100);
Reservervaion r2 = ReservationFactory.getReservation(2,101);
}
I am new to java and am trying to pass variables like in the following example from one class to another, im wondering is this possible and how i would go about it if it is.
As this code does not work as it is not static.
Main Class
public class testAll
{
public static void main(String[] args)
{
One one = new One();
Two two = new Two();
}
}
The first class:
public class One
{
public int test = 4;
public int getTest()
{
return this.test;
}
}
The second class:
public class Two
{
public void value()
{
System.out.print("Var is: " + One.getTest());
}
}
Thanks,
Naz
Lets consider this, if you want to access a variable in Class A from Class B then Class A needs to know about Class B.
public class A {
public A(B classB){
this.classB = classB;
}
public void printValue(){
System.out.println(this.classB.getTest());
}
}
Now you will need to pass an instance of ClassB to ClassA in the constructor so that Class A has a reference to ClassB when it calls printValue();
ClassB b = new ClassB();
ClassA a = new ClassA(b);
b.getTest();
a.printValue();
You have to create an instance for class One first. Try this
public void value()
{
One one_object = new One();
System.out.print("Var is: " + one_object.getTest());
}
public class Two {
private One one;
public Two(One one) {
this.one = one;
}
public void printValue() {
System.out.print("Var is: " + one.getTest());
}
}
public class Main {
public static void main(String [] args) {
One one = new One();
Two two = new Two(one);
two.printValue();
}
}
There are two way - pass a reference or pass a value:
public class One {
private int value = 0;
public One(final int value) {
this.value = value;
}
public int getValue() { return value; }
}
public class Two {
private One one = null;
public Two(final int value) {
this.one = new One(value);
}
public Two(final One one) {
this.one = one;
}
public int getValue() { return one.getValue(); }
}
When passing a reference to a One instance, the value is read from One and will only change it the value held inside the One instance changes. When passing a primitive (int, boolean ...) the value is copied and "owned" by the Two instance. Read some more about the differences of references and values to grasp the idea. It's quite simple, once you get the idea.
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.