Private, protected Access Modifiers with a class

Why cant we use private and protected access modifiers with a class?
Thanks.

Matiz wrote:
>
Public access allows you to extend a parent class in some other package. If you only want users to extend your class rather than instantiate it directly, make the class abstract and design for extension.Agreed. However, would the same argument be not true for the default access at the class level? No. Default access would only allow you to extend a parent class in the same package (as opposed to some other package).
Now my confusion is why is a class allowed default access at the top level and not protected?Because protected for a top-level class makes no sense. The protected keyword provides member access to any other class in the same package and extending classes outside the package. A top-level class isn't a member of a class, by definition, so there's nothing that protected would do provide differently than public.
So, the two access modifiers for a top-level class are public and default. Public allows access to the class outside the package, whereas default restricts access to the class within the package.
~

Similar Messages

  • Accessing function with a Class

    Hi
    I have a mp3player that I want to include in another flash
    movie. The mp3player is a movie clip with an actionscript class
    attached to it. I can use the mp3 player fine and it works
    perfectly, but I have a slight problem when I want to change one of
    the variables in the class. The class contains get and set methods
    to change the playlist etc, and the only way I can think of to
    access them is to create a new player object and call the functions
    on that object. This kind of works- I can call the function and it
    resets the playlist value, but for some reason the constructor in
    the class is called straight afterwards and the playlist reverts
    back to the default. I have a feeling this has something to do with
    the fact that the actionscript class is attached to the player
    movieclip, but I'm not an expert at using OO design in flash, and
    so can't be certain.
    I hope someone can help- I'm sorry I can't post any of the
    code in the class, but it's a file I bought and the copyright won't
    allow me to do so.
    Thanks in advance
    S

    It's hard to attemp an answer when you don't supply any code.
    Do you have access to the .fla file? What variables are are
    involved? What are the instance names.? Are you working with the
    .swf file?
    If you are wrking with a .swf perhaps there is a LoadVariable
    which is loading the play list from a text file which is probably
    located in some folder under the SWFs root folder.on your system.
    Check there and if so, let me know and I'll try to assist.

  • Java class access modifiers

    Why java class cannot have private and protected access modifiers?

    class X {
      private class y {}
    }should compile just fine. A top-level private class makes no sense because you wouldn't be able to see it. As for protected, I don't know.

  • Protected and public access modifier - exact difference

    Hi everybody,
    Please help me to give an exact difference between protected access modifier and public
    Protected: Classes with in the same package as well as subclasses can access.
    Public : Classes outside the current class can access while declaring public.
    My doubt is that what is the practical difference between public and protected.
    I searched the net , but the information was not satisfactory to solve my confusion.
    Thanks & regards
    Parvathy

    Obviously doubt = lacks the ability to think for
    oneself.When one person raises a doubt, that does n't mean that he lacks the ability to think . He/She might have thought about it and if he didnt get a proper clarification then it will be posted in the forum.
    In such cases please dont discourage others who are ready to answer the subject.Without knowing the actual intention , i request you please dont reply like this

  • Default class access modifier

    What is the default access modifier for a class? I can't seem to find it in the tutorials...
    Thanks
    Jim

    The default access is the same for top level classes that do not specify access explicitly as for other identifiers. Package.
    This single source file will create two class files in the same package. Only other classes in the package can see these top level package access classes.
    And, yes, this is a bad idea. In the case of some build tools, errors in a compile can cause the public class to compile, but the package class to fail. After that, the compiler will not be able to determine what source file to compile for the package level class. This is an error that confuses many developers. I do not recommend this practice. Put each top level class in its own source file.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Understanding the combination of inheritance, packages and access modifiers

    I am working on a problem to help my practical understanding of accessing inherited members and methods from a different package using both inheritance and instance variable.
    Unfortunately, I am totally lost when I tried to set this up and understand what was happening.
    Problem:
    Create a class named "classA" under package "pack1" with 4 members (int pub_a, int priv_a, int prot_a, int def_a) and methods (pub_func1, priv_func1, prot_func1, def_func1). Mark the members and methods with 4 different access specifiers (public, private, protected, and default)
    Create a class named "classB" under package "pack2", ClassB will inherit classA of package pack1. ClassB will have 2 members (int pub_b, int priv_b) and methods (pub_func2, prot_func2) with 2 different access specifiers (public, protected)
    Try accessing the members of class classA in package pack1 inside class classB of package pack2. Find out what members and methods are accessible and not-accessible through inheritance.
    Create an instance of class classA inside class classB of package pack2. Find out what members and methods are accessible and not-accessible through the instance.
    Note: In your solution, comment out the lines that are in-accessible with the actual error message at the top of the comment.
    So I produced the following code (I don't think i set this up right):
    //filename A.java
    package pack1;
    public class A {
         public int pub_a;
         private int priv_a;
         protected int prot_a;
         int def_a;
         public int pub_func1() {return 1;}
         private int priv_func1() {return 2;}
         protected int prot_func1() {return 3;}
         int def_func1() {return 4;}
    //filename B.java
    package pack2;
    import pack1.A;
    public class B extends A{
         public     int pub_b;
         private int priv_b;
         public int pub_func2() { return 5; }
         private int priv_func2() { return 6; }
         //directly inherited fields, at least one should be accessible?
         pub_a = 1;
         priv_a = 1;
         prot_a = 1;
         def_a = 1;
         int i;
         // directly inherited methods, at least one should be accessible?
         i = pub_func1();
         i = priv_func2();
         A a = new A();
         //not sure what's accessible here, as no error red underlines appear
         a.pub_a = 1;
         a.priv_a = 1;
         a.prot_a = 1;
         a.def_a = 1;     
    }I would be interested to know how one would approach and address this problem.

    //filename B.java
    package pack2;
    import pack1.A;
    public class B extends A{
         public     int pub_b;
         private int priv_b;
         public int pub_func2() { return 5; }
         private int priv_func2() { return 6; }
         //directly inherited fields, at least one should be accessible?
         pub_a = 1;//true
         priv_a = 1;// false
         prot_a = 1;//true
         def_a = 1;//false
         int i;
         // directly inherited methods, at least one should be accessible?
         i = pub_func1();//true
         i = priv_func2();//false
         A a = new A();
         //not sure what's accessible here, as no error red underlines appear
         a.pub_a = 1;//true
         a.priv_a = 1;//false
         a.prot_a = 1//false;
         a.def_a = 1;//false
    }Edited by: fun_with_me on May 31, 2008 8:30 AM

  • Use of public access modifier in main method

    I want to know what is the significance of public access modifier with main (String args[]) method. Like generally we write
    public static void main(String args[])
    But if we write
    private static void main(String args[])
    OR
    protected static void main(String args[])
    then also its working properly.............
    then what is the use of public keyword..........................
    Regards
    Ajay Pratap Singh

    then what is the use of public keyword..........................Convention, I believe. And I think newer versions of the JVM require it.
    P.S. Relax a bit on the punctuation overuse. Many folks around here find that a bit irritating, and you probably don't intend to send that kind of a message. Cheers!

  • I'm confused about protected access - any insight ?

    I'm trying to understand how the protected access modifier works. I have tried to compile some example code and I'm seeing behavior which appears to go against what the text I'm using claims should happen. To wit:
    My understanding is that any subclass and any class in the same package has access to the protected member of a class. Default access (when no access modifier is used at all) allows access only to classes in the same package.
    I have the following two classes:
    //--------  Parent.java ---------------
    package testpkg.p1;
    public class Parent
        public int x = 7;
        protected int getXValue ()
            return x;
    //--------- Child.java --------------
    package testpkg.p2;
    import testpkg.p1.Parent;
    public class Child
        extends Parent
        public static void main (String[] args)
            Child child = new Child();
            System.out.println("Child X: " + child.getXValue() + "\n");
            System.out.println("Parent X: " + child.testParent());
        public int testParent ()
            Parent parent = new Parent();
            return parent.getXValue();
    }I get the following compilation error:
    $ javac -d ../lib Parent.java Child.java
    Child.java:18: getXValue() has protected access in testpkg.p1.Parent
    return parent.getXValue();
    ^
    1 error
    Now it seems to me that everything should compile fine since the Child class is a subclass of the Parent class, and as such should have access to the protected member method getXValue(). However this obviously isn't the case. It seems that the behavior is more like what is described for default access, i.e. no access by any class outside of the package, no matter if it is a subclass or not.
    Can anyone enlighten me on this ? Am I missing something obvious ?
    Thanks in advance for any feedback.
    -James

    You know that you don't have to use the "protected"
    modifier.Yes you do.
    In fact, when I learned Java, it was called
    "package" scope, not protected. But the same
    principle applies.No, the principles outlined above and in the Java Language Spec apply.
    "protected" or "package" means that only classes
    within the package itself can have access. You do not
    actually have to place any modifier at all since this
    is the default scope.No, protected adds the ability to access ex-package super class members from a child class instance. Try compiling the above example without specifying protected access.
    Pete

  • Static main(String args[]) access modifiers possible

    main(String args[]) can have private as access modifier?

    hi,
    yes of course this is possible, because main is at the end only a method like each other. But you have to know, that you cannot use this method from outside. so no application will start, if the main() of the Main-class has a private as modifier.
    You can use this class as an applet.
    So be carefull doing this
    regards

  • Private or Protected access for super class variables

    What is the best practice...
    Assume there is a class hierachy like
    Person (Super class) / StaffMember/ Professor (Sub class)
    1) The best way is to keep all the instance variables of each and every class private and access the private variables of super classes through subclass constructors (calling "super()")
    Ex:-
    public class Person {
    private String empNo;
    public Person (String empNo) {
    this.empNo = empNo;
    public class Professor extends Person {
    private String ........;
    private int ...........;
    public Professor (String pEmpNo) {
    super(pEmpNo);
    OR
    2)Changing the access level of the super class variables into "protected" or "default" and access them directly within the sub classes...
    Ex:-
    public class Person {
    protected String empNo;
    public Person () {
    public class Professor extends Person {
    String ........;
    int ...........;
    public Professor (String empNo) {
    this.empNo = empNo;
    Thank you...

    i'd think that you'd be better off relaying your initial values through the super class's constructor that way you'll get cleaner code, there's a possibly of inconsistency with option 2. i.e. you can then write code in your super classes to generally handle and properly initialize the instance variables while in the case of option 2, you'll have arbitrary constructors performing arbitrary initialization procedures

  • Can not access a member of class Test with modifiers ""

    Hi!
    I am trying to get a application into a applet, but I just get this errormessage:
    Exception: Java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class Test with modifiers ""
    Anyone that have any idea whats wrong here?
    Best regards Raymond

    Post class where the exception was ocurred.

  • Inheritance and access control - "private protected"

    I'm reopening an old topic, seems to have been last discussed here 2-3 years ago.
    It concerns the concept of restricting access to class members to itself, and its subclasses. This is what "protected" does in C++ and "private protected" did in early versions of the Java language. This feature was removed from Java with a motivation along the lines of not being "simple", and "linear" (in line with the other access modes, each being a true subset of the next). Unfortunately, the article which explained Sun's position on this keyword combination seems to have been removed from the site, so I haven't been able to read its original text.
    But regardless of simplicity of implementation or explaining Java's access modifiers to newbies, I believe it is a fundamental part of OO programming for such an access mode to exist. The arguments for having the standard "private" mode in fact also apply for having a C++-style "protected" mode. (Arguing that classes within a package are related and it therefore doesn't hurt to also give them access to Java's "protected" members, is equally arguing that "private" is unneccessary, which noone of course believes.)
    The whole concept of inheritance and polymorphism and encapsulation builds on the access modes private, protected, and public (in the C++ senses). In Java the "package" concept was added - a nice feature! But I see no justification for it to negate the proper encapsulation of a class and its specializations.

    What effect upon inheritance other than hiding members
    from subclasses is there?
    None. And I cant think of another declaration that prevents members from being inherited but private.
    Of course the onus comes on the programmer with Java's
    definition of "protected" - but
    1) there is rarely a single programmer working within
    a package
    The point was the package is a unit which does not hide from itself. Just like all methods within a class can see each other, all classes within a package can, and all packages within a program can.
    2) it muddies the encapsulation in the design - when
    you see a "protected" method someone else, or yourself
    some time ago - wrote, how do you know if the design
    intention is to have it accessed solely by the class
    and its subclasses, or if it is indeed intended to be
    shared with the whole package? The only way to do
    this today is to always explicitly specify this in the
    comments, which may be lacking, inconsistent, and
    abused (since it isn't enforced).Encapsulation would be implementation hiding. Not method hiding. The only thing you should probably allow out of your package is an interface and a factory anyway.
    I understand where you are coming from, but I really have not had occasion to take issue with it. I can't think of a real codeing situation where this is required. OTOH, I can't think of a coding situation where I need to access a protected method from another class either.

  • Reopened topic "private protected" modifier

    I respond to reply in thread <http://forums.sun.com/thread.jspa?threadID=503004>. There I posted following:
    I would like to express that something like "private protected" is really missing. I develop packages for modelling of engineering structures. I have real and clear example why I need this. I was very surprised that I cannot open fields for subclasses only! Therefore I have to use "private" because I dont want to see these fields from another classes. It does not make sense in this way.
    There is my example:
    Imagine that there is a model for analysis of a engineering structure. This model can be 2D or 3D. Im developing three packages. First, the most abstract, contains classes useful in both 2D and 3D branches. For example class AbstractMassPoint, which has field mass. Second package is 2D brach and third package is 3D branch. In 2D and 3D branch are subclasses of AbstractMassPoint named MassPoint. I both versions of MassPoint class are relationships using mass field and one natural solution is access it directly without using getMass() method. But I like encapsulation and I dont want to see this field outside class AbstractMassPoint except subclases MassPoint which are natural subclasses. Modifier protected is too weak. I dont want to see this field in classes from package. Therefore current state is private modifier and something like getMass() methods. You can see source codes on my page (keywords: kitnarf's library, fydik).
    I like Java, but this is wrong. Why it is not possible?

    kitnarf wrote:
    There is my example:
    Imagine that there is a model for analysis of a engineering structure. This model can be 2D or 3D. Im developing three packages. First, the most abstract, contains classes useful in both 2D and 3D branches. For example class AbstractMassPoint, which has field mass. Second package is 2D brach and third package is 3D branch. In 2D and 3D branch are subclasses of AbstractMassPoint named MassPoint. I both versions of MassPoint class are relationships using mass field and one natural solution is access it directly without using getMass() method. But I like encapsulation and I dont want to see this field outside class AbstractMassPoint except subclases MassPoint which are natural subclasses. Modifier protected is too weak. I dont want to see this field in classes from package. Therefore current state is private modifier and something like getMass() methods. You can see source codes on my page (keywords: kitnarf's library, fydik).
    I like Java, but this is wrong. Why it is not possible?Although you might have a case for this very specific application how does it apply to the other million possible applications that one might create? If 900,000 of them could use it in such a way that it makes the code better then it is a good idea. But if only 1 could use it then it isn't.
    Given that I can get to private members if I want but it just isn't convenient to do so. So all you are doing is providing encouragement to someone to do the right thing. The best way to do that is correctly design the classes in the first place and provide correct and complete documentation. That works much better that trying to find ways to restrict it.

  • Access level with no modifier

    Hello
    Hello
    I read in Access Level in
    http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
    and know that I cannot access "no modifier" from a subclass. So I try
    public class Exam {
    String myString; //no modifier keyword
    public class Exam1 extends Exam{
    void setMyString(){
         myString="test";
    There is no compile error. It can be seen that I can access "myString" of super class Exam from subclass.
    Could you please tell me why
    Thanks

    Because those two classes are in the same package (In your case, that means in the same folder). The access level "with no modifier" is called the default access level or "package private".

  • Why does protected access also allow access from classes in same package

    Having been asked the question and found myself unable to answer it, I wonder if anyone can explain the reasoning why protected access implies the default access as well?

    Sure:
    ---------- class A ------
    package pkg;
    public class A
    protected static int _a;
    private int _i;
    public A() { _i = _a++; }
    public String toString() { return "instance "+_i; }
    --------- class B ------
    package pkg;
    public class B
    public B() { A._a = 27; }
    --------- class C -----
    public class C extends pkg.A
    -------- class main ----
    public class main
    public static void main(String[] args)
    pkg.B b1 = new pkg.B();
    pkg.A a1 = new pkg.A();
    pkg.B b2 = new pkg.B();
    C c1 = new C();
    System.out.println("a1 is "+a1);
    System.out.println("c1 is "+c1);
    The above classes are legal and compile and when
    run, the output is:
    a1 is instance 27
    c1 is instance 27
    (Please note, this is just an example of what is allowed and why I'm curious as to the advantages of this permitted behaviour, NOT what I would ever write!)

Maybe you are looking for

  • Could not resolve s:ViewNavigatorApplication to a component implementation

    Hi, I am getting this error while building my Flex mobile project using ant build. It compiles preopely through flash Builder but gives the error : "Could not resolve <s:ViewNavigatorApplication> to a component implementation" when compiling with ant

  • HT4061 How to activate Nike+ipod in my iphone 5S

    Dear All, I want to activate nike+ipod app in my iphone 5s, but due to some reason which i don't know I enaable to activate nike+ipod application. Please do the needful... regards Viral Umate

  • Error connecting to Oracle 11g Database

    Hi All I am testing .NET connectivity to Oracle 11g and I am not successful for a while. I've tried to connect to database using library included in Oracle 10.2.0.3 Client and as a result I've got "invalid username or password" error. Then I've tried

  • Hardware key id

    Hello, I installed mini sap but my license has expired. Now , I need my Hardware key (HWID)  but I don't know how can get it? . I tried to go to saplicense.exe but I don't find. I am a beginner so I don't know a lot . Thanks a lot.

  • Creating Setup Package in Netweaver Administrator MI

    Hello everybody,<br><br> after a long searching to a clear manual about setting up Mobile Infrastructure client, and after a lot of reading the typical spaghetti manuals of SAP, I started to create a Device Configuration to test the MAM 3.0<br><br> I