R
R
Roman_SV2016-12-27 20:08:51
Java
Roman_SV, 2016-12-27 20:08:51

Why are public methods and variables not visible in the same package?

I work in IntelliJ Idea.
We have the Human class as a separate file.

public class Human {
    public int age = 0;
    public String name = "Nobody";
    protected int height = 1;
    protected int strength = 1;

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public int getHeight() {
        return height;
    }

    public int getStrength() {
        return strength;
    }

In the same package, another Life class is also a separate file:
public class Life {
    Human petrovich = new Human();
    petrovich. // тут по ctrl+space мы узнаём, что нет доступа к методам и атрибутам Human
}

Why doesn't an instance of the Human petrovich class have access to the methods and attributes of the Human parent class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim Loginov, 2016-12-27
@Roman_SV

You didn't create a procedure in the Life class:

public class Life {
    Human a = new Human();
    public void test(){
        a.getAge();
    }
}

And everything works.

D
docker1, 2016-12-27
@docker1

Please remove public and protected fields. All fields must be private. Have their setters and getters make the scopes what you need. The rest has already been answered.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question