HemaSundar
HemaSundar

Reputation: 1293

How to use objects created in Parent class inside Child class?

public class test1 
{
    classA obj = new classA()
}


public class test2 extends test1 
{
    public void test() {

        //unable to access object 'obj'
    }
}

From the child class I am unable to access the object that is created in the parent class.

Upvotes: 0

Views: 105

Answers (4)

Chris
Chris

Reputation: 934

You may need to run these from two separate files that are assigned to the same package. File 1 called test1.java

package TestStuff;
import java.util.List;
public class test1 {
     List <String> newStringList;
}

File 2 called test2.java

package TestStuff; #same package at test1.java
public class test2 extends test1 {
    public void test(){
        String d = "dog";
        for (int i = 0; i < d.length(); i++){
            newStringList.add(d);
        }
    }
}

Now I can access the object I created in test1.java as if it was already defined in my current class.

Upvotes: 0

SMA
SMA

Reputation: 37023

You gave default access and i see them both in default package, so you should be able to have access the same. If you defined them in different packages then you should expose getter method in Parent class like:

public classA getClassA() {
    return obj1;
}

Or you could mark that field as protected like below:

protected classA obj = new classA()

Upvotes: 0

billz
billz

Reputation: 45410

To allow derived class access parent member, you need to specify protected or public

public class test1 {
    protected classA obj = new classA()
//  ^^^^^^^^
}


public class test2 extends test1 {
    public void test() {

        // now you can access obj in test2
    }
}

Upvotes: 1

Eran
Eran

Reputation: 393841

You haven't specified any access modifier for the obj member of test1 class, which makes it package private by default. Therefore, your test2 sub-class would have access to it only if it's in the same package as test1. If you change it to protected classA obj = new classA();, you'll be able to access it no matter in which package test2 is located.

That said, it is a better practice to define all the members as private, and give access to them via accesssor methods.

Upvotes: 3

Related Questions