-3

Here, I created 5 classes named as child1, child2 childrens, Mom and HelloWorld. I created a variable pcount in childrens class that is exnted by two class child1 and child2.

This is the code for reference.

import java.util.*;
class Mom{
    public void fun(){
        child1 ch11=new child1("child1");
        child2 ch22=new child2("child2");
        for (int i=0;i<HelloWorld.al.size();i++){
            if(HelloWorld.al.get(i)==1){
                ch11.pcount++;
            }else{
                ch22.pcount++;
            }
        }
    }
    
}
class Childrens{
    String name;
    public int pcount=0;
}
class child1 extends Childrens{
    child1(String n){
        name=n;
    }
}
class child2 extends Childrens{
    child2(String n){
        name=n;
    }
}
class HelloWorld{
    static ArrayList<Integer> al=new ArrayList<>();
    public static void main(String[] args){
        child1 ch1=new child1("child1");
        child2 ch2=new child2("child2");
        Mom m=new Mom();
        al.add(1);
        m.fun();
        System.out.println(ch1.pcount);
        System.out.println(ch2.pcount);
    }
}

Output came is: 0 0

but Expected output is: 1 0

So, Can you help me to figure out what is the problem in this code?

  • 2
    Welcome to Stack Overflow! This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Oct 12 '22 at 18:21
  • Having said that... You never modify `ch1` or use it in any way. Why do you expect any value on it to change from its default? Why would you expect `ch1` to have a value of `1` but not expect `ch2` to have that value, even though you treat them both identically? – David Oct 12 '22 at 18:22
  • 1
    `ch11` is not `ch1` - you operate on `ch11` in `fun` but then expect `ch1` to be updated when you print it out. Perhaps add `ch1` and `ch2` as parameters to `fun` and eliminate the local declares - but only you know what you are trying to do. – Computable Oct 12 '22 at 18:24

1 Answers1

0

ch1 and ch2 have no relation to Mom in your code

You're just modifying ch11 and ch22 within the scope of Mom

If you want to affect ch1 and ch2, you could have an ArrayList<Childrens> in Mom that stores type Childrens

You could then add a method such as addChild(Childrens c) in Mom that adds a child to Mom

In that case, fun could iterate across the ArrayList<Childrens> and directly change values of ch1 and ch2 (or potentially even more Childrens added to the ArrayList)

mmartinez04
  • 323
  • 1
  • 1
  • 4