简体   繁体   中英

Real example for access identifiers [public, protected, private]

I am new to OOP.

I know that there are three identifiers and they should be used in different situations. I have also read lots of discussion regarding whether or not it is dangerous to use the "public" identifier too causally. But I don't really understand why this is dangerous.

Let say I have a windows application or web application. In those applications I declared some public methods or variables, how is that dangerous? I mean, my applications accept user input and then produce output, so in what ways can it be dangerous? How can others or other programs attack or take advantages or somehow do some damage to the application because of the "public" identifier.

Can anyone describe a real life example? Thanks.

Modifier    | Class | Package | Subclass | World
————————————+———————+—————————+——————————+———————
public      |  ✔    |    ✔    |    ✔     |   ✔
————————————+———————+—————————+——————————+———————
protected   |  ✔    |    ✔    |    ✔     |   ✘
————————————+———————+—————————+——————————+———————
no modifier |  ✔    |    ✔    |    ✘     |   ✘
————————————+———————+—————————+——————————+———————
private     |  ✔    |    ✘    |    ✘     |   ✘

Private:

Methods,Variables and Constructors

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Note

Variables that are declared private can be accessed outside the class if public getter methods are present in the class. Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Protected

The protected access modifier cannot be applied to class and interfaces.

Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Note

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Public

A class, method, constructor, interface etc declared public can be accessed from any other class.

Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

http://javarevisited.blogspot.com/2012/10/difference-between-private-protected-public-package-access-java.html

Let's take it to a meta level instead, and pretend that we are instances of a class Person .

We have some information about us - name , age , gender , weight , height , hairColor , eyeColor , and so forth. Mostly, this is information that we expose to the outside world through incidental interaction, so this could be considered to be "public" information. I mean, there's no sense in hiding your eyeColor unless you really wanted to...

Now, there are a few things that we don't tell the outside world, but are willing to tell our children. These are things like recipes, how to solve math problems, how to do taxes, how to deal with nasty breakups, etc. These functions are passed down via inheritance, and as such, can only be referenced in terms of an ancestral hierarchy. We would call this "protected" information, or a "protected" method of solving these problems.

There are also the things that we keep only within the family, like the number of times your puppy has chewed up your sister's favorite doll, or where the family inheritance is. We could consider this, with a bit of wordsmithing, to be private within the hierarchy of our family.

Finally, there are the things we just don't share with anyone else, but we need this information to function on a daily basis. This is what we consider to be "private".

Now, the illustration of that meta example was a classical example of Access Modifiers .

  • public indicates that everyone can see it and do what they will with it. That is to say, if you were to have a public accessible name, then I could at a whim, just change it to "Overflow Prime", and there'd be nothing you could do about it.

  • protected indicates that this field or method is only visible to those that directly inherit from the class. So, for instance, Child extends Parent would imply that I get access to Parent 's protected methods and fields.

  • "package-private", or simply "no modifier", is a field or method that is only accessible and modifiable within the scope of a package. It means that the fields are public as far as the package is concerned, but completely unknown to anything outside of the package.

  • private is a field or method that only the instance of that class can use and manipulate directly. Even if there's an inheritance chain, if the method or field is private, there's no way that the child classes can get to it.

Now, what does that mean in terms of your real world example?

Let's say, for instance, your web application handled sensitive information, like financial records. If I were able to modify the instance of the class that held my weekly pay check stub from a meager $600 to a sizable $79,999, then I would have both compromised the integrity of your application, exposed a major financial bug (from which bad things happen), and would have been cut a decent weekly check for my trouble.

That's the idea behind encapsulation . I want to expose only the bare minimum hooks and information to the outside world to ensure the integrity of my application, and to ensure that someone can't cut themselves a check they didn't deserve.

Here is your answer: https://softwareengineering.stackexchange.com/questions/143736/why-do-we-need-private-variables

In short, it is a matter of maintaining complexity and reusability in the long run. By ensuring that variables are private to a class, you can stop fellow programmers (or even your future self) from modifying anything major that affects the internals of your classes.

As for a real world example, imagine your future self sitting down with some code you wrote and trying to locate where a certain bug occurs. After days of hunting you determine the culprit: A member variable of an instance of your class was modified. And not even by you, but by a fellow member of your team who depended on that variable.

Now you have a big problem. Private variables save you from all this trouble.

I have tried to answer the question with the help of very basic code and comments.

package com.oops;

public class Modifiers {
    public int a = 0;
    private int b = 0;
    protected int c = 0;
    int d = 0;

    public static void main(String[] args) {
        new TestPublic().getAndPrintA();
        new TestPrivate().cannotGetB();
        new TestProtected().getProtected();
        new TestDefault().getDefault();
    }
}

class TestPublic {
    public void getAndPrintA() {
        Modifiers modifiers = new Modifiers();
        modifiers.a = 10; // Public variables can be used from anywhere.
    }
}

class TestPrivate {
    public void cannotGetB() {
        Modifiers modifiers = new Modifiers();
        // modifiers.b; //Compile time error: The field Modifiers.b is not
        // visible
    }
}

class TestProtected {
    public void getProtected() {
        Modifiers modifiers = new Modifiers();
        modifiers.c = 10; // Visible here, but will not be visible to the
                            // outside world.
        // Protected means package and subclass
    }
}

class TestDefault {
    public void getDefault() {
        Modifiers modifiers = new Modifiers();
        modifiers.d = 10; // Visible here, but will not be visible to the
                            // outside world and subclass.
        // Default means only within package.
    }
}

Although the concepts has been well explained by others but I think question required a real example. Following is a try to explain concept around. Please mind the package name: myarea

 package myarea;

    public class MyHome{
         private int frontDoorLock;
         public int myAddress;
         int defaultWifiPaswd;
    }

Now the comments ( works/doesn't work ) explain it clear In another file but same package: myarea

package myarea;

public class MyBedroom{
public static void main(String[] args) {
       MyHome a = new MyHome();
       int v1 = a.myAddress; // works
       int v2 = a.defaultWifiPaswd; // works
       int v3 = a.frontDoorLock; // doesn’t work
    }
}

Another file different package: neighbourArea

package neighbourArea;

import myarea.MyHome;

public class NeighbourHome{
public static void main(String[] args) {
       MyHome a = new MyHome();
       int v1 = a.myAddress; // works
       int v2 = a.defaultWifiPwd; // doesn’t work
       int v3 = a.privateVar; // doesn’t work
}

Originally I shared this in support to explain one of article in Java code geeks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM