Access to the method without static - java

I have 2 class, class B and A
public class B
private Car fiat;
public boolean trueOrFalse() {
return fiat.methodFromClassCar();
}
In class A i want to use this result from this boolean, something like:
public class A
public int xyz(){
if (trueOrFalse()==true){
doSomething();
}
}
Always i making static all, but now i cant do this. Is there better way ?
Create a new object in class A:
Car cr = new Car();
and then using
cr.trueOrFalse();
is good way ? but what i code wrong here ?

You have different options :
-> have a Car as attribute of class A
public class A{
private Car c;
public int xyz(){
if (c.trueOrFalse()){ //==true is 100% useless
doSomething();
}
}
}
call with A test = new A(); /*then*/ test.xyz(); //c = new Car(); in constructor of A
-> give to the method a Car as parameter
public class A{
public int xyz(Car c){
if (c.trueOrFalse()){
doSomething();
}
}
call with A test = new A(); /*then*/ test.xyz(new Car()); or Car c = new Car(); /*then*/test.xyz(c);

Related

JAVA generics constructor issue

I'm studying JAVA generics nowadays and find out some weird situation.
class A{
public void mInA(){
System.out.println("mInA");
}
}
interface I{
public void mInInterfaceI();
}
class B extends A implements I{
public void mInInterfaceI(){
System.out.println("mInterfaceI");
}
}
class MyList <TP1, TP2>{
MyList(TP1 data1){
this.data1 = data1;
}
TP1 data1;
TP2 data2;
MyList<TP1, TP2> next;
}
public class GenericPrepare {
public static void main(String[] args){
B obj = new B();
MyList<A,B> anchor = new MyList<>(obj);//Curious
anchor.data2 = new B();
anchor.next = null;
}
}
My constructor is designed to put TP1 as input. So I must input 'A' type reference as argument in above remark.
But when i input 'B' type reference as argument, JAVA is not complaining about it.
I have no idea what's going on here.
The MyList<A,B> constructor expects an A object as parameter, but because B extends A, B is actually assignable to A -> your code works.

Implement a common function accepting argument of two different classes?

I have two classes A and B and they both have a common field in them, and I want to create a function in which if I pass Class A object then I want to set that common field value to the passed value and if I pass Class B object then I want to set that common field value to the passed value. Can anyone please tell me how can I do this, I am new to Java Generic Classes.
Otherwise I would have to make two different functions OR I would have to make an if and else which would decide that passed object belongs to which class ??
Class A
public class A{
int footer;
public void setFooter(int fo) {
footer = fo;
}
}
Class B
public class B{
int footer;
public void setFooter(int fo) {
footer = fo;
}
}
Class D
public class D{
public void change_footer(T generic_param, int value) {
generic_param.setFooter(value);
}
}
Class HelloWorld
public class HelloWorld{
public static void main(String []args){
Here I want to call
A a = new A();
new D().change_footer(a, 5);
B b = new B();
new D().change_footer(b, 5)
}
}
Thank You
And if I got all of the question wrong, and nor A nor B are generic, AND the type of field is fixed.
then you mean something like:
class D {
/*public <T extends Super> would be muuuch nicer here as well!*/
public /*static*/ <T> void change_footer(T obj, int data) {
//otherwise, you could just cast to Super...and set dat field.
if (obj instanceof A) {
((A) obj).setField(data);
} else if (obj instanceof B) {
((B) obj).setField(data);
} // else ... ?
}
}
Original answer:
Easy peasy (the "straight forward" implementation produces the desired results.):
class A<T> {
T daField;
public void setField(T pField) {
daField = pField;
}
public T getField() {
return daField;
}
}
class B<T> extends A {//empty
}
class Test {
public static void main(String... args) {
B<Object> testB1 = new B<>(); //
testB1.setField(new Object());
System.out.println(testB1.getField());
B<String> testB2 = new B<>();
testB2.setField("blah blah");
System.out.println(testB2.getField());
B<Integer> testB3 = new B<>();
testB3.setField(42);
System.out.println(testB3.getField());
}
}
System.out:
java.lang.Object#6d06d69c
blah blah
42
It get's (little) more complicated, when you want to instantiate Ts ...but still possible/other question. :)
Edit to your comment:
If there's only one common field, then why not:
/*abstract */class Super<T> {
T daField;
public void setField(T pField) {
daField = pField;
}
public T getField() {
return daField;
}
}
? ...and:
class A<T> extends Super { ... }
class B<T> extends Super { ... }

Best way to share updated data between classes in java

I am working on a projects and I have run into a problem, I don't know the best way to share updated data between classes. The current way that I am doing this is by having a static instance of my class in it and having all the other classes change the instance and not the original class.
public class A{
public static volatile instance;
public B b = new B();
public C c = new C();
public D d = new D();
public A(){
this.instance = this;
b.changeData();
}
}
public class B{
public void changeData(){
A.instance.d.changeSomethingInD();
}
}
Now, all the changes that D made to its variables can be accessed by B and C. Is there a better way to do this?
Edit 1: The problem that I have is having updated variables accessible to all the other classes. This was what I was doing before:
public class MainClass extends JavaPlugin{
private RegionLoader rLoader;
private ClassesLoader cLoader;
private MessageHandler mHandler;
private PlayerDates pDates;
public MainClass(){
dirMaker();
mHandler = new MessageHandler(this);
pDates = new PlayerDates(this);
cLoader = new ClassesLoader(this);
rLoader = new RegionLoader(this);
}
//getters and setters
}
But the problem is if the RegionLoader changes somithing within itself, the ClassesLoader won't have the updated variables and will work with the old ones, or would it?
Why not just pass A into the constructor of B. This way you wouldn't need to use static data.
public class A{
public B b;
public C c = new C();
public D d = new D();
public A(){
b = new B(this);
b.changeData();
}
}
public class B{
private A a;
public B(A a){
this.a = a;
}
public void changeData(){
a.d.changeSomethingInD();
}
}
You could also checkout the observer pattern.

Java: how does a component know its owner

Suppose I have a class A and a class B.
public class A {
private B b;
public A() {
this.b = new B();
}
public B getB() {
return this.b;
}
}
public class B {
public String getSome() {
return "Get some!";
}
}
I know I can get B through A, because A has (or owns) B: new A().getB().
But if I have B, can I get A?
Sure, just add routine getA() in you class B, and change the line in your constructor to
public A() {
this.b = new B(this);
}
This of course assumes your class B has a constructor which accepts an A, e.g.,
public B(A a) {
this.a = a;
}
B needs an explicit reference to its owner:
public class B {
private final A owner;
public B(A owner) {
this.owner = owner;
}
public A getOwner() {
return owner;
}
}
And in A:
public A() {
b = new B(this);
}
Nope. There is no such thing as an 'owner' in Java. Any object can be referenced by any number of other objects.
If you need B to always be bound to an instance of A, make B an inner class of A:
class A {
B b = new B();
class B {
String getSome() {
// this will refer to the enclosing A
return A.this.toString();
}
}
}
An inner (non-static) class always has an implicit reference to the enclosing instance and cannot exist without it. In order to instantiate B from outside, you need a nasty syntax: B b = new A().new B();
No you cannot. B has no reference to A.
No.
Class a has reference to class B, but class B has no reference to class A. References are one way only.
No, that's not possible. You're looking for backreferences, but we have to create them in the code if needed.
If you want to collect all referencers to B, you could do this with a constructor or with a factory (pattern) that creates B's. I'll show the factory:
public class B {
private static Set<? extends Object> referencers = new HashSet<? extends Object>();
private B(){} // no public constructor
public static create(Object parent) {
// cooperative approach, the caller should pass "this"
referencers.add(parent);
}
public static remove(Object parent) {
referencers.remove(parent);
}
}
you can also use inner classes
package test;
public class A {
B b = null;
public B getB()
{
return b;
}
public class B {
public A getA()
{
return A.this;
}
}
public static void main(String[] args) {
B b = new A().new B();
}
}

Two questions on inner classes in Java (class A { class B { } })

Sorry for the bad title, but I couldn't think of a better one.
I'm having a class A and a class B which is kind of a sub class of A, like so:
(Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?)
class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
B b = a.new B();
A c = ??? b ??? // get "a" back
}
}
From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick.
Second one:
class A {
void print() {
System.out.println("This is class A.");
}
class B {
void print() {
// <--- How to access print() of class A (like this.A.print() or smth)?
System.out.println("This is class B.");
}
}
}
You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far.
Thanks in advance. :)
There doesn't seem to be a way to access the outer class from outside. But you can do it like this:
class A {
int i = 0;
class B {
final A outer = A.this;
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = b.outer // get "a" back
}
}
ClassName.this will be the instance of the outerclass associated with the instance of an inner class.
You can access it with the ParentClass.this syntax from within the inner class.
e.g.
public class Outter
{
class Inner {
public Outter getOutter()
{
return Outter.this;
}
}
public Inner getInner(){
return new Inner();
}
}
class Runner{
public static void main(String[] args){
Outter out = new Outter();
Outter.Inner inner = out.getInner();
System.out.println(inner.getOutter().toString());
}
}
[Edit: My answer is appropriate for C# programmers, but I can't guarantee that its applicable to Java.]
B is an inner class, not a subclass of A. Additionally, B does not hold an instance of A, so your code as is cannot return any instance of A.
You need to restructure your classes as follows:
class A
{
public class B
{
public A Parent;
public B(A parent)
{
this.Parent = parent;
}
}
}
Now your B class has a field 'Parent' which returns its parent. You can use these classes as follows (this is C# syntax, because I don't know if Java has a different syntax for instantiating inner classes):
public static void Main(String[] args)
{
A parent = new A();
A.B child = new A.B(child);
A backToParent = child.Parent;
}
Of course, creating your B class in this way seems little funny: technically, you can pass in any parent. It would probably be better to rewrite your A class with a method which returns a B:
class A
{
public class B
{
public A Parent;
public B(A parent)
{
this.Parent = parent;
}
}
public B getChild()
{
return new B(this);
}
}
public static void Main(String[] args)
{
A parent = new A();
A.B child = A.getChild();
A backToParent = child.Parent;
}
this seemed to work for me
class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = (A)b.getClass().getDeclaredField("this$0").get(b);
}
}

Categories

Resources