I want advice on what should I do:
I have a class A and B such that
public class A {
int result;
int a;
public A(){
result =0;
a = 5;
B myB= new B();
System.out.println(result);
}
public void main(){
A myA= new A();
}
}
public class B extends Thread {
public B(){
start();
}
public void run() {
addition1();
}
public void addition1() {
////////HERE trying to do///////
result = a+5;
}
}
Unfortunally, I need to use, peferable two classes and must two threads and the addition will be perform in the second thread and update the first thread.
This is just an example I came that shows what my issues are. my real code was far too long to post in here.
Thanks
I assume that when you say that you want to update from one thread to another you should have had Class A also as an extension of Thread or a Runnable object. However Class A in your example is not a Thread extension and can be updated by an operation in B (which is another thread) in a usual way like you can update a shared variable in multi threaded scenario. Just expose a setter method for the result variable in Class A and update it from the B class method (addition1) which is running in new thread. Therefore you would have updated a shared instance (of class A) being operated upon by main thread (the first thread) from another thread (spawned during construction of Class B) method (addition1)
You can try with Callback Mechanism to get the result back one it's computed.
For more info read inline comments.
Sample code:
interface Callback {
public void execute(int result);
}
// make it abstract and don't provide implementation of execute method here
abstract class B extends Thread implements Callback {
private A a;
// pass the reference of Class A to access it
public B(A a) {
this.a = a;
start();
}
public void run() {
addition1();
}
public void addition1() {
int result = a.a + 5;
//result is computed now call pass the value to the waiter and that's A
execute(result);
}
}
class A {
int result;
int a;
public A() {
result = 0;
a = 5;
B myB = new B(this) {// pass the reference of Class A
#Override
public void execute(int result) {
// This is the computed result that is returned from Class B
System.out.println(result);
}
};
}
}
Related
I create a hierarchy from an abstract class and two children that are used in class F and pass them to the service
#Getter
abstract class A {
private final B b;
public A(B b) {
this.b = b;
}
abstract void doSomething();
}
#Getter
class B {
private final String someProperty;
}
class C extends A {
public C(B b) {
super(b);
}
#Override
void doSomething() {
super.getb().getSomeProperty();
}
}
class D extends A {
public D(B b) {
super(b);
}
#Override
void doSomething() {
super.getb().getSomeProperty();
}
}
#RestController
class F {
#Autowired
private Service service;
#GetMapping
public void methodOne() {
A a1 = new C(new B("ccc"));
service.make(a1);
}
#GetMapping
public void methodTwo() {
A a1 = new D(new B("ddd"));
service.make(a1);
}
}
#Service
public class Service {
public void make(A a) {
a.doSomething();
}
}
The construction that I described above in case we have a lot of clients who call our API will there be any problems in thread safety with the state of our abstract class or not?
"Thread Safety" thing comes into the picture when multiple threads are trying to manipulate same object and by allowing to do so may end up with inconsistent state of the Object which is obviously not acceptable for any application.
Your question is about the Object you've declared in your abstract parent class, now as I said earlier the problem will only be there if multiple threads are using the same object, since you're creating new objects every time the service method is getting called, you are safe why?, because the scope of the object is limited to the method and multiple threads can not use the same object as for each method call you'll have a different object.
Now consider this case, in this case thread safety is a concern,
#Service
class UnSafeClass {
private MyClass myClassObject;
public void doSomething() {
myClassObject.changeData();//Same object will be used by multiple threads
}
}
So, your current implementation does not have any thread safety concerns but we should definitely need to clarify on where exactly you need to take care of thread safety.
I have created 3 classes, one superclass "a" and under a two subclasses "b" and "c". I am creating an instance of c, give it an integer "n" and then use subclass b to do some calculation. The problem I am having is that when I create an instance c to call b, the data technically belong to the superclass a/c right? so when i create an instance of b with
b b_instance = new b();
inside the instance of c,
the b calc() function I call would return 0. I guess it's because b has it's own eco-sphere of data?
How do I do this?
2)
Also, how do i call the superclass function of the same name?
Thanks!
public class prog
{
public static void main(String args[])
{
c c1 = new c();
c1.run();
}
}
class a
{
private int number;
void set_number(int n)
{
number = n;
}
int get_number()
{
return number;
}
int calc()
{
return number*2;
}
}
class b extends a
{
int calc()
{
// calling the superclass function calc, then subtract
return super.calc() - get_number();
}
}
class c extends a
{
void run()
{
set_number(1);
b b1 = new b();
System.out.println(b1.calc());
}
}
infinite loop problem
public class prog
{
public static void main(String args[])
{
c c1 = new c();
c1.run();
}
}
class a
{
void calc_a()
{
System.out.println("") ;
}
void calc_b()
{
calc_a(); // meaning the calc_a() in the superclass
}
}
class b extends a
{
void calc_a()
{
super.calc_b();
}
}
class c extends a
{
void run()
{
b b1 = new b();
b1.calc_b();
}
}
b b_instance = new b();
inside the instance of c, the b calc() function I call would return 0.
I guess it's because b has it's own eco-sphere of data?
How do I do this?
A "couple" of possible ways. I'd consider extending c from b, this way c gets all the functionality of a and b, something like...
class c extends b {
void run() {
set_number(1);
System.out.println(calc());
}
}
IF, however, this is not feasible (for some reason or other), then you need to pass the value that c has to b, something like...
class c extends a {
void run() {
set_number(1);
b b1 = new b();
b1.set_number(get_number());
System.out.println(b1.calc());
}
}
Now, having said that, this "smells" to me. What's the point of extending from a just so c can perform b? It would set off alarm bells to me.
The problem is, if your call c#calc, it's just going to a's calc method ... which, based on run, doesn't seem to be what you want to achieve, so it's all just a big mess
2)
Also, how do i call the superclass function of the same name?
Because calling calc directly would cause a StackOverflowError because you're constantly calling yourself.
In this case, you're taking the operation that a is doing and making a modification to it. This is a common practice in OO languages.
Side notes...
Java (and the Java community) already have a well defined set of coding practices. You should take the time to learn them, it will make your code easier to read and make it easier for you to read other peoples codes.
Start with Code Conventions for the Java TM Programming Language
Class names should start with a capital letter and methods are in camelCase, for example...
class A {
private int number;
void setNumber(int n) {
number = n;
}
int getNumber() {
return number;
}
int calc() {
return number * 2;
}
}
Updated...
class a {
void calc_a() {
System.out.println("");
}
void calc_b() {
calc_a(); // meaning the calc_a() in the superclass
}
}
class b extends a {
void calc_a() {
super.calc_b();
}
}
class c extends a {
void run() {
b b1 = new b();
b1.calc_b();
}
}
The question you need to ask yourself is, why does b need to override calc_a? Why not override calc_b? It would solve the issue
how do i override it?
class b extends a {
//void calc_a() {
// super.calc_b();
//}
#Override
void calc_b() {
super.calc_b();
}
}
I have following situation and would like to know the best way to design my solution
public abstract class A {
public abstract A getHelper();
public abstract void launchHandle();
public static A initHelper(String condition) throws Exception {
if ( condition == 'xyz') {
return C.getHelper();
} else {
return B.getHelper();
}
}
}
public class B extends A {
protected static A b;
#Override
public A getHelper() {
b = new B();
return b;
}
#Override
public void launchHandle() {
System.out.println("Launching Handle");
}
public String getName() {
return "I am from Class B";
}
}
public class C extends A {
protected static A c;
#Override
public A getHelper() {
c = new C();
return c;
}
#Override
public void launchHandle() {
System.out.println("Launching Handle from C");
}
public String getValue() {
return "I am from Class C";
}
}
**Executor class**
public class Executor {
public static void main(String[] args) {
A aa = a.initHelper(condition);
}
}
Now in the above approach, i am unable to access methods like aa.getName() from Class B OR aa.getValue() from Class C, which makes sense. However how to get these methods in executor class? Executor does not know anything about Class B & C and should not know. Executor is only aware of Class A, but want to access methods SubClass methods from B & C which are extended from Class A.
Please help design this and what could be best way to solve this.
Thanks in advance.
Executor is only aware of Class A, but want to access methods SubClass methods from B & C which are extended from Class A.
If you take a closer look at your code, you will notice that the only contract constant across all your classes is the launchHandle method (baring getHelper and initHelper which are simply used for instantiating the right subclass). There is no real relation between B and C other than the fact that their instantiation is controlled by A.
This is how I would consider approaching the problem :
Executor Factory
Make Executor an abstract class rather than making it the entry point of your program :
public abstract class Executor {
public abstract void performTask();
public static void execute(String condition) {
Executor executor = null;
if ( condition.equals("xyz")) {
executor = new AExector();
} else {
executor = new BExecutor();
}
executor.performTask();
}
}
Executor implementations
Create a different implementation for operating on B called BExecutor :
public class BExecutor extends Executor {
public void performTask() {
System.out.println("launching handle from B");
//create or get data to perform the task on
B b = new B();
String name = b.getName();
System.out.println("I am from "+name);
}
}
Create a different implementation for operating on C called CExecutor :
public class CExecutor extends Executor {
public void performTask() {
System.out.println("launching handle from C");
//create or get data to perform the task on
C c = new C();
String value = c.getValue();
System.out.println("I am from "+value);
}
}
Your main method can then look like this :
public static void main(String []args) {
Executor executor = Executor.execute(condition);
}
And for some reason, if you do find some common contract between B and C, you an always create an interface which both B and C can implement and use a reference of this interface instead of using a B or C reference.
Add getName and getValue to A as abstract methods.
i'm relativly new to java and experimantating a bit with javafx
i want to change a variable from class A while using a method from class B
Main: thats the main class, it contains all the needed stuff(shows the primaryStage etc) it does have an constructor, so its not creating an actual "main-object"
public class Main extends Application {
Sub sub = new Sub();
int a;
// stuff
public void aMethod() {
sub.subMethod();
}
}
Sub: this class solely surpose is to change the variable a, it does not contain a constructor to create a "sub-object"
public class Sub {
//stuff
subMethod(){
int a = 5;
}
if i put the line Main main; in the Sub class, the program will give me a nullpointer exception, if i'm calling the subMethod().
ok...i guess cause i didnt actually create the main object... so far so good.
BUT... if i put in the line Main main = new Main(); the program wont even start giving me an "exception while running application" error
the strange thing though is, if i put the line Main main = new Main(); in the subMethod...
subMethod(){
Main main = new Main();
int a = 5;
}
...the damn thing actually works...(well its slow, guess because with every calling of the method its creating a new object)
why is that so?
and how is it done correctly? :)
(using methods of other classes to "overwrite" variables)
regards
Red
You should not create more than one instance of Main in your program. Probably Main is not the best place to store mutable state (class members), but if you want that, you need to pass the instance of Main to subMethod (and make a public, or provide a public setter method):
public class Main extends Application {
Sub sub = new Sub();
public int a;
// stuff
public void aMethod() {
sub.subMethod(this);
}
}
public class Sub {
//stuff
subMethod(Main main){
main.a = 5;
}
So you want a method to change the value of another class's fields. There are a few ways to do this. If you have this class
public Class A {
private int a;
...
public void setA(int a) {
this.a = a;
}
}
You can do something like this
public Class B {
private static A instance;
....
public static void setA(int a) {
instance.setA(a);
}
}
Or you can take the A in as a parameter to the set method
public Class B {
...
public static void setA(A a, int val) {
a.setA(val);
}
}
If you want direct access to the fields on A you have to make them public (this is usually not what you want to do as it gives complete access rather than just giving just the access the other classes require)
Public Class A {
public int a;
...
}
Then you can do
Public Class B {
...
public static void setVal(A a, int val) {
a.a = val;
}
}
Also if you don't have the method setA in B as static you'll have to call it on an instance of B like
B b = new B();
b.setA(a, val);
Where as if it's static you call it on the class B
B.setA(a, val);
I have a Java assessment that gets marked by a robot. Whenever I upload my assignment it shows a screen like this.
A good object-oriented design places each method into the most appropriate
class. The most appropriate class for a method should be the same class as
the data fields that that method needs to access. If you don't place a method
into the right class, then this will most likely increase the amount of
communication that is required between your classes.
The score below measures the amount of communication between your classes. A
lower score is better.
19 method invocations between classes
7 arguments passed between classes
15 results returned between classes
Amount of communication = invocations + 2*inputs + 2*outputs = 63
Now what exactly does "method invocations between classes", "arguments passed between classes" and "results returned between classes" mean?
Method invocations between classes
As your class contains their own methods if you want to call the method from another class you have to use an instance of this class.
For example :
class A{
public void methodA(){
}
}
class B{
public void methodB(){
}
}
If I want to call methodA() from the class B I must use this:
public void methodB(){
A a = new A();
a.methodA(); // method invocation between classes
}
Argument passed between classes
This time methodA() will need an argument, and B as a field which could be used as argument.
class A{
public void methodA(int argument){
}
}
class B{
private int fieldB = 42;
public void methodB(){
}
}
To call methodA() from B you will pass an argument from a class to another.
public void methodB(){
A a= new A();
a.methodA(fieldB); //Argument passed between classes
}
Results returned between classes
And now methodA() returns a result this is the code.
class A{
public int methodA(){
return 42;
}
}
class B{
private int fieldB;
public void methodB(){
}
}
To use/handle the returned value of the methodA() from the class B you'll have to do this:
public void methodB(){
A a= new A();
fieldB = a.methodA(); //Result returned between classes
}
I'd have to say:
method invocations between classes
Suppose you have classes X and Y. This would be any time class X calls some method on class Y.
e.g.,
class Y
{
public void foo() { }
}
class X
{
public void someMethod()
{
Y y = new Y();
y.foo();
}
}
arguments passed between classes
Could possibly mean one of two things.
Either you are accessing a field of another class directly.
class Y
{
public int number;
}
class X
{
public void someMethod()
{
Y y = new Y();
int yNum = y.number;
}
}
Or a method was called where arguments are supplied. (most likely case)
class Y
{
public void foo(int arg) { }
}
class X
{
public void someMethod()
{
Y y = new Y();
y.foo(56);
}
}
results returned between classes
Received a value from a method of another class that returned a value. e.g., getters or other methods.
class Y
{
public int foo() { return 42; }
private int number;
public int getNumber() { return number; }
}
class X
{
public void someMethod()
{
Y y = new Y();
int yFoo = y.foo();
int yNumber = y.getNumber();
}
}