Arianule
Arianule

Reputation: 9043

trying to understand access tomembers within a package

Good morning

I am learning Java and trying to understand the access to class members inside a package. I have to files in MemberAccess directory and called the package unitOne.MemberAccess(is that right?)

Here is the simple example.

package unitOne.MemberAccess;

public class Parent 
{
    private String secret = "This is my secret"; 
    protected String inherit = "All my money";

    int age = 100; 

    public void singInShower()
    {
        System.out.println("la-di-da");
    }
}   

new I created a seperate file in the same package called OtherPerson.

package unitOne.MemberAccess;

class OtherPerson
{


    public static void main(String[]args)
    {
        OtherPerson op = new OtherPerson();
        System.out.println(op.inherit);
        System.out.println(op.age);
    }   

}

The problem is that I get a compile time error explaining to me that the symbol cannot be found. But in my understanding protected and default members in the same package as another class can be viewed by that class.

Regards Arian

Upvotes: 1

Views: 50

Answers (5)

Jwalin Shah
Jwalin Shah

Reputation: 2521

You need to create object of Parent class in Otherperson class.

So, you need to write Parent op = new Parent() instead of OtherPerson op = new OtherPerson();

Upvotes: 2

Zohaib
Zohaib

Reputation: 7116

A member of one class (whether private, public, protected or default) is Never visible to other Class. NEVER....That would be a night mare. Accessing other members and visibility of other members come into play when one class Inherits other class. So either you need to extend class, implement parent child relationship. Then what you are saying would be true

and yes, where I live, its Good Evening here at this point of time :)

Upvotes: 1

Mahesh
Mahesh

Reputation: 34625

 OtherPerson op = new OtherPerson();

op is an instance of type OtherPerson. The OtherPerson and Parent classes has no relation and thus op cannot be used to access Parent class members.

Upvotes: 3

solendil
solendil

Reputation: 8458

op is an OtherPerson object and has no age property. The class Parent has an age property, though. Replacing OtherPerson op = new OtherPerson(); with Parent op = new Parent(); should work.

Upvotes: 1

SteeveDroz
SteeveDroz

Reputation: 6136

Your OtherPerson doesn't inherit your Parent.

Try replacing the second line of your OtherPerson.java with class OtherPerson extends Parent.

Upvotes: 1

Related Questions