Creating instance of member variables - java

Hi this is a basic question, but kindly bear with me.
I have two classes and on class has a reference of another class. How can i create the instance of second class which is present in first class at the time creation of instance of first class. Are any utility present for this.
Code ::
class A {
B b;
}
class B {
int member;
}

In a Contructor (like Robert Kock already said)
class A {
B b;
public A(){
b = new B();
b.member = 5;
}
}
Directly as Attribute
class A {
B b = new B(5);
}
With Initializer
class A {
B b;
{
b = new B();
b.member = 5;
}
}

Within the constructor of the first class:
class A
{
public A()
{
b = new B();
}
B b;
}
Or even like this:
class A
{
public A()
{
}
B b = new B();
}

A general solution would be:
public class A {
private final B b;
public A(B b) {
this.b = b;
}
}
...
A a = new A(new B());
It becomes interesting when both instances refer to each other, then you need to use a setter in at least one of the classes:
public class B {
private A a; // the field cannot be final in this case
public void setA(A a) {
this.a = a;
}
}
....
B b = new B()
A a = new A(b);
b.setA(a);
The answers where the class is creating the other instance itself are not a general solution.

Related

Associate one and only one object

Hello I have one question.
I have Class A and Class B. I create one object A and multiple objects B. But I want only one B can set with A.
e.x
class A{}
class B{ private A a;}
public static void main(String[] args){
A a= new A();
B b= new B();
B c= new B();
b.setA(a);
c.setA(a);//Sould not assign it.
}
Here is one way to implement such a concept.
Code
class A {}
public class B
{
private static final HashSet<A> setA = new HashSet<>();
private A a;
public void setA(A a)
{
if (!setA.contains(a))
{
this.a = a;
setA.add(a);
}
}
public A getA() { return a; }
public static void main(String[] args)
{
A a0 = new A();
A a1 = new A();
B b0 = new B();
B b1 = new B();
B b2 = new B();
b0.setA(a0);
b1.setA(a1);
// Below two operations fail silently
b2.setA(a0);
b2.setA(a1);
System.out.println(b0.getA());
System.out.println(b1.getA());
System.out.println(b2.getA());
}
}
You can even throw a custom exception instead of failing silently.
Output
george_17092021_1434.A#568db2f2
george_17092021_1434.A#378bf509
null
Conclusion
Doing so should help in achieving what you want. However, I do not know if this is something to be used professionally or not. Please comment if you face any problems.

Down Casting to indirect subclass does not work?

public class A
{
public void printA(){
System.out.println("A");
}
}
public class B extends A
{
public void printB(){
System.out.println("B");
}
}
public class C extends B
{
public void printC(){
System.out.println("C");
}
}
public class test {
public static void main(String[] args)
{
A a = new B();
a.printA(); // work
B b = (B) a;
b.printB(); // work
C c = (C) b;
c.printC(); // not work throw java.lang.ClassCastException
}
}
i have three classes A and B and C
C extends from B and B extends from A
why down casting work from A to B, and does not work from B to C ,although the relation between them like A and B , B is parent of C so how it work JVM??
Classes can only be cast to their parent classes, they have no knowledge about their subclasses.
Since your object is an instance of B, it does not implement methods of C.
This will work:
A a = new C();
a.printA(); // work
B b = (B) a;
b.printB(); // work
C c = (C) b;
c.printC(); // work

How do we make a java class immutable if it has a member variable of another user defined class?

Recently in an interview for Java Developer role, I was asked how do I make Class A immutable if it has a member variable, which is an object of Class B and in a situation where Class B is external to the project and cannot be edited by the programmer moreover class B might even have a member variable of its own which is an object of another user defined class. I gave it a lot of thought and told the interviewer there is no way unless class B has implemented and exposed a method to deep clone itself.
The interviewer though wasn't convinced. Is there really a way to make such a class immutable?
If I can remember correctly this was the situation he explained. He wanted me to make class A immutable, what would have been the best answer?
final public class A {
final private B b;
A(B b) {
this.b = b; // Class b might/might not be cloneable
// this.b = (B)b.clone();
}
public B getB() {
return b;
// return (B)b.clone();
}
}
class B // external cannot edit
{
C c;
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
}
class C // external cannot edit
{
int i;
String j;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getJ() {
return j;
}
public void setJ(String j) {
this.j = j;
}
}
Don't expose B to the world. So do not have a method which return B.
Instead identify the methods in B, which don't mutate B and let A implement these methods by calling the same method in b.
So if B has a method calcSomething() a should have a calcSomething() methocd which just does return b.calcSomething().
You may use something like this:
final public class A {
final private B b;
A(B b) {
this.b = cloneB(b);
}
public B getB() {
return cloneB(b);
}
private static B cloneB(b){
B newB = new B();
C c = new C();
c.setI(b.getC().getI());
c.setJ(b.getC().getJ());
newB.setC(c);
return newB;
}
}
It that case Class A is 100% immutable.
Update: Also you can use reflection or seralization to get deep copy of class (if class has deep hierarchy), for example using GSON for seralization:
private static B cloneB(b){
String tmp = new GSON().toJson(b);
return new GSON().fromJson(tmp, B.class);
}
or so on

how to access an instance of a class from its instance variable

So I have this scenario
class A:
public class A {
B b = new B();
public void doSomething() {
// this does something
}
}
and class B:
public class B {
public B() {
// need to access A
}
}
The problem is that I need to access the instance of A from the A's instance variable B. How do I do that?
You may simply pass the instance of A to B:
class A {
B b;
A() {
b = new B(this);//<-- A's instance
}
}
class B {
A a;
B(A a) {
this.a = a;
}
}
If class Bneeds to access an existing instance of A then you must provide the B instance with a reference to the A instance.
class B {
private A a;
B(A a) {
this.a = a;
// do something with a
}
}
then
A a = new A();
B b = new B(a);
If you need access to the A only within the constructor then you don't need to store a local copy of the reference.
You must create new object from instance A
A aa = new A();
OR
public class B extends A {
public B() {
// need to access A
}
}
Inner Class seems like the best thing to do ,
public class A {
B b = new B();
private int tryToAccess;
public void doSomething() {
// this does something
}
public class B{
public B()
{
tryToAccess=5;
}
}//B ends
}//A ends
Note:This is just one way of going about it , here you can access A's private variables from class B

Java: Get access from nested class to main class?

Code:
public class A{
B b = new B();
public class B{
public void fun(){ send(A); }
}
I want to do something with all A object in B.
I can create method in A class:
private A getThis(){return this;}
But is it other solution (some keyword)?
Try this code inside your inner class.
A.this
It should give you a reference to the enclosing instance from the outer class.
Here is a small example.
public class A {
private B b = new B();
public class B {
public void fun() {
}
public A getEnclosing(){
return A.this;
}
}
public static void main(String[] args){
A a = new A();
System.out.println(a == a.b.getEnclosing());
}
}
Try
B b = new B(this);
Then B contructor
public B(A a) {
this.a = a;
}

Categories