I am a newbie to Java (I come from the C/C++ background) and I was having a hard time figuring out how to allocated memory of a data member in one class from another. For eg,
Class A
{
B bInA;
C cInA;
public void foo(someValue)
{
cInA = new C();
cInA.foo(bInA, someValue)
}
public static void main(String args[])
{
A myA = new A();
myA.foo(xyz)
// myA.bInA.value should be equal to xyz
}
}
Class B { ... }
Class C
{
public void foo(bInA, someValue)
{
bInA = new B();
bInA.value = someValue;
}
}
Can I do something like this in java?
Any help will be much appreciated.
----EDIT-----
Class A
{
B bInA;
C cInA;
public void foo(someValue)
{
cInA = new C();
bInA = new B();
cInA.foo(bInA, someValue)
}
public static void main(String args[])
{
A myA = new A();
myA.foo(xyz)
// myA.bInA.value should be equal to xyz
}
}
Class B { ... }
Class C
{
public void foo(bInA, someValue)
{
bInA.value = someValue;
}
}
Unless I'm misunderstanding your intention (change value of bInA from C), your recent edit seems to work fine. Here's my java version of your pseudocode.
class A
{
B bInA;
C cInA;
public void foo(int someValue)
{
cInA = new C();
bInA = new B();
cInA.foo(bInA, someValue);
System.out.println(bInA.value);
}
public static void main(String args[])
{
A myA = new A();
myA.foo(123);
// myA.bInA.value should be equal to xyz
}
}
class B { int value; }
class C
{
public void foo(B bInA, int someValue)
{
bInA.value = someValue;
}
}
Output
123
Java does not have pass-by-reference; rather, all you ever have are references to objects, and those references must be passed by value. So your code is roughly equivalent to something like this in C++:
class A {
private:
B *bInA = NULL;
C *cInA = NULL;
public:
void foo(someValue) {
cInA->foo(bInA, someValue);
}
static void main() {
A *myA = new A();
myA->foo(xyz)
// myA->bInA->value should be equal to xyz
}
}
int main() {
A::main();
return 0;
}
class B { ... }
class C {
public:
void foo(bInA, someValue) {
bInA = new B(); // defeats the point of having passed in a bInA
bInA->value = someValue;
}
}
(Except that the C++ code has memory leaks, since you allocate some things without freeing them, whereas in Java that's not an issue.)
Related
There are two java classes both having main function. Now i have to call object of first class to the second and object of second class to first. Whenever i m doing this it is giving stack overflow exception. Is there any way to call these simulatneously?
First class :
public class ChangePasswordLogin extends javax.swing.JFrame {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String message = null;
RandomStringGenerator rsg = new RandomStringGenerator();
MD5Generator pass = new MD5Generator();
PopUp popobj = new PopUp();
ForgotPassword fpemail = new ForgotPassword();
Second class:
public class ForgotPassword extends javax.swing.JFrame {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String message = null;
String useremail;
PopUp popobj = new PopUp();
RandomStringGenerator rsg = new RandomStringGenerator();
MD5Generator pass = new MD5Generator();
ChangePasswordLogin cpl = new ChangePasswordLogin();
You've got recursion going on where class A creates an instance of class B in its constructor and class B creates an instance of A in its constructor or initiation code. This will continue on and on until you run out of memory. The solution is not to do this. Use setter methods to set the instances outside of the constructor and initiation code.
This can be demonstrated simply with:
// this will cause a StackOverfowException
public class RecursionEg {
public static void main(String[] args) {
A a = new A();
}
}
class A {
private B b = new B();
}
class B {
private A a = new A();
}
Solved with setter methods:
// this won't cause a StackOverfowException
public class RecursionEg {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.setB(b);
b.setA(a);
}
}
class A {
private B b;
public void setB(B b) {
this.b = b;
}
}
class B {
private A a;
public void setA(A a) {
this.a = a;
}
}
Substitute ForgotPassword and ChangePasswordLoging for A and B.
Or you could get by like the code below, where you take care to create one instance of each type:
public class RecursionEg {
public static void main(String[] args) {
A a = new A();
}
}
class A {
private B b = new B(this);
}
class B {
private A a;
public B(A a) {
this.a = a;
}
public void setA(A a) {
this.a = a;
}
}
for educational purposes I am trying to understand how to access a list's maximum element(originally in class B) (in this case from a Double list) through another class e.g class A. The list is used in a different class in which elements are added to it (e.g class C). However, when I add something like this to my class A to access my Max element, it does not seem to work: // help is appreciated :) and the error I usually get is noSuchElementException
just a method of class A
void printMax () {
B b = new B();
Double result;
result = Collections.max(b.array);
System.out.println("MAX:" +result);
}
here is my class B:
public class B {
public ArrayList<Double> array;
B() {
array = new ArrayList<Double>();
}
public void doSomething() {
int i;
for(i = 0; i < array.size(); i++) {
System.out.println("Doubles:" +array.get(i));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new B().doSomething();
}
}
Here is my class C that adds to my ArrayList.
Class C {
public String line;
C () {
}
public void linePicker() {
B b = new B();
Scanner dScanner = new Scanner(line);
while (dScanner.hasNext()) {
if (dScanner.hasNextDouble()) {
b.array.add(dScanner.nextDouble());
break;
} else {
dScanner.next();
}
}
dScanner.close();
b.doSomething();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new C().linePicker();
}
}
According to the javadocs (http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max(java.util.Collection,%20java.util.Comparator)), it throws that exception when the Collection is empty. You initialize b.array, but haven't added to it yet before calling max().
I recently came across this question and have not been able to find a solution to it. I hope I will get a convincing answer here.
Question : Let A be a non abstract class which is extended (separately) by two classes B and C. Now the task is to allow only one instance of the these classes to be created. If the client code tries to create a second instance of any of these classes, then an exception should be thrown.
A obj11 = new A(); // Fine.
A obj12 = new A(); // thrown an exception.
B obj21 = new B(); // OR
A obj21 = new B(); // both these should be fine
But shouldn't allow 2nd instance of class B to be created.
Thanks in advance.
P.S. : This is different from singleton.
The following should do it. In the real world there should be some synchronized keywords. All crammed into one file for simplicity.
public class A {
static HashSet<Class> thereCanBeOnlyOne = new HashSet();
public A() {
Class c = this.getClass();
if (thereCanBeOnlyOne.contains(c))
throw new RuntimeException();
thereCanBeOnlyOne.add(c);
}
static public class B extends A {}
static public class C extends A {}
public static void main(String[] args) {
A a1 = new A();
B b1 = new B(); // OK
C c1 = new C(); // OK
C c2 = new C(); // throws exception
}
}
Is this ok for you?
public class A {
private static created = false;
public static A create() {
if (created) {
throws new RuntimeException();
} else {
created = true;
return new A();
}
}
protected A() {
}
}
public class B extends A {
private static created = false;
public static B create() {
if (created) {
throws new RuntimeException();
} else {
created = true;
return new B();
}
}
protected B() {
}
}
public class C extends A {
private static created = false;
public static C create() {
if (created) {
throws new RuntimeException();
} else {
created = true;
return new C();
}
}
protected C() {
}
}
You can create A, B, and C using:
A a = A.create();
B b = B.create();
C c = C.create();
class A {
static int i;
{
System.out.println("A init block"+ ++i);
}
}
class B extends A {
static int j;
{
System.out.println("B init block"+ ++j);
}
}
class C extends B {
static int k;
{
System.out.println("C init block"+ ++k);
}
public static void main(String abc[])
{
C c =new C();
}
}
In the code above, we can easily count the number of objects created for each class.
But if i want to check the number of object created explicitly , i mean if I create C's object using new C(), or B's object using new B(), then it should give the count accordingly
Take for example,
C c2=new C();
B b2=new B();
So it should give the output of B's count as 1 and not 2.
public class Foo {
private static int fooCount = 0;
public Foo() {
if (this.getClass() == Foo.class) {
fooCount++;
}
}
public static int getFooCount() {
return fooCount;
}
}
public class Test {
static int count;
Test() {
count++;
}
public static void main(String[] args) {
Test t = new Test();
Test t1 = new Test();
NewTest nt = new NewTest();
System.out.println("Test Count : " + Test.count);
System.out.println("NewTest Count : " + NewTest.count);
}
}
class NewTest extends Test
{ static int count;
NewTest()
{
Test.count--;
NewTest.count++;
}
}
OP :
Test Count : 2
NewTest Count : 1
Lets say I have three classes:
Class A:
public class A {
private String s;
public A() {
s = "blah";
}
public void print() {
System.out.println(s);
}
}
Class B:
public class B{
private A a[];
public B(){
a = new A[100];
for (int i=0; i<100;i++) {
a[i] = new A();
}
}
public void print() {
for (int i=0; i<100; i++) {
a.print(); //SHOULD BE a[i].print();
}
}
}
Class Main:
public class Main {
public static void main(String args[]) {
B b = new B();
b.print();
}
}
Why do I get an outputpattern like B##, where # is a number. I think it has something to do with indirect adressing but im not quite sure. Why doesn't it print out 100 s?
You are printing the array rather than the object in the array. As a result, it is printing the address of the object (the number) and the object it is a member of.
I suspect you wanted to call each of the prints, you should, in B.print(). You are also missing an increment for i, meaning it will loop indefinitely.
for(int i = 0; i < 100; ++i)
{
a[i].print();
}