Java Access Modifier

Do we need to have a single public class in a java file.If yes then how does the following code work?
class Bas{
public static void main(String args[])
System.out.println("hello");
is the access specifier in the above case public or default.
Sudeep

Hi Sudeep,
It is not a condition that you have atleast one public class. If you want to set required access for your class in that package, then do so. Else by default, it has the default access.
However, please note these 2 things:
1) You can have only one public class in a file. And could contain any number of defaut access classes.
2) If you specify a class as public, you have name that class as the same name of the Public class.
Hope this sums up for you.
Rajesh

Similar Messages

  • Java access modifiers

    I still confuse with this.
    The difference between both keywords is just subclass can't access and override 'private', so as if class 'DerivedClass' doesn't have the private method (although implicitly they have). Subclass can access or override methods with 'protected' keyword. Right??
    So if I have a base class to -say- generate a document, and maybe someday I want to create a derived class, which code is better :
    //1st
    public class BaseGenerator {
        private String generateTopDoc() {
            //call checkSyntax here
        private String generateBottomDoc() {
            //call checkSyntax here
        private boolean checkSyntax(String s) {...}
        public String generateDocument() {
            return generateTopDoc().concat(generateBottomDoc());
    //2nd
    public class BaseGenerator {
        protected String generateTopDoc() {
            //call checkSyntax here
        protected String generateBottomDoc() {
            //call checkSyntax here
        private boolean checkSyntax(String s) {...}
        public String generateDocument() {
            return generateTopDoc().concat(generateBottomDoc());
    //3rd
    public class BaseGenerator {
        protected String generateTopDoc() {
            //call checkSyntax here
        protected String generateBottomDoc() {
            //call checkSyntax here
        protected boolean checkSyntax(String s) {...}
        public String generateDocument() {
            return generateTopDoc().concat(generateBottomDoc());
    //4th
    public class BaseGenerator {
        private boolean checkSyntax(String s) {...}
        public String generateDocument() {
            //return full document, checkSyntax called here for both top and bottom part of doc
    //5th
    public class BaseGenerator {
        protected boolean checkSyntax(String s) {...}
        public String generateDocument() {
            //return full document, checkSyntax called here for both top and bottom part of doc
    }When should i use 'private', and when should I use 'protected'?

    >
    So if I have a base class to -say- generate a
    document, and maybe someday I want to create a derived
    class, which code is better :Do not generalize unless you have something to generalize with.
    "Someday" you may not need to derive anything from it as well. Or you may find that your original design was completely wrong and now you need 5 new classes and need to rework the original system so that the new functionality will work.
    So given that you have nothing to generalize from now, that means that the only correct solution is to use private.

  • 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.

  • Acces specifiers and Access Modifiers in java

    what are Access specifiers?
    what are Access modifiers?
    Whether both of them are same or is there any difference?

    As far as I know "access specifier" == "access modifier".
    To me, they both mean "the Java Language word which specifies the visibility of a class or class attribute".
    http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
    ... but I'm no expert.
    Cheers.

  • Default/package/none access modifier

    Hi,
    I was hoping for some discussion on the default/package/none access modifier. It's always really bugged me that we have public, private, protected, and then "none", while it seems to me that it would be less confusing, and more consistent to use the keyword "package", or maybe even "default".
    Then, source code would look like
    public class MyClass{
        public int getValue() {}
        private void setValue() {}
        protected void someMethod() {}
        package int justForPackage() {}
    }I know this concept has come up before, but the books I've read which mention this topic haven't offered any actaul justification/explanation for why there isn't some keyword.
    Anyway, are there any insights as to why java is this way, and any reasons why java should or shouldn't be changed to include the package access modifier.

    A good example is within a tightly grouped package (usually should be this way) you may have some cooperative classes that access methods.
    // one .java file
    public class SomeHelper {
       private void method() {
         new ClassForUsers().accessHiddenLogic();
    // next .java file in same package
    public ClassForUsers {
        /* default-access */ void accessHiddenLogic() {
    }But, you may want to allow users to subclass your ClassForUsers, without giving them access to the hidden logic method directly:
    // another .java file in a different package
    public class UsersSubclass extends ClassForUsers {
        public void userMethod() {
            // can't do this
            accessHiddenLogic();
    }This could be for either business logic or security reasons. So, package level access can be very useful. However, I've seen that in practice it is avoided because it isn't obvious what is going on.

  • Access Modifier: Only Subclass, not package wide?

    Hello fellow programmers
    I'm looking for an access modifier that allows access to a method or member only from a class and it's subclasses. So it must be weaker than private because subclasses have access and stronger than protected because I don't want it to be accessible package wide.
    Is there such a modifier in Java?
    Regards
    Der Hinterwaeldler

    There used to be in a very early version of the language but it was dropped for clarity. IIRC it was called "private protected." Now you have to settle for "protected."
    This makes kind of sense since you have more control over the classes in your own package than over the subclasses that are not necessarily written by you ... If you can't trust other classes in the same package maybe you should put the class in a new package...

  • Default access modifier

    Hello,
    Can someone tell me what the default access modifier is in Java:
    -for methods
    -for member variables
    Thanks in advance,
    Balteo

    Friendly. Accessible to any other classes in the package.

  • Access modifiers ignored !?!

    Hi
    please, have a look at the code below and let me know your opinions
    // ------------- source file 1 ------------------------
    package pckg1;
    public class Dog {
         final public static void main (String[] args) {
              pckg2.Puppy puppy = new pckg2.Puppy("Spot");
              System.out.println(puppy.getName());
    // ------------- source file 2 --------------------
    package pckg2;
    class Puppy {
         String name;
         public Puppy(String name) {
              this.name = name;
         String getName() {return name;}
    Each class belongs to a different package. Obviously if you compile Puppy first and attempt compiling Dog the compiler will complain about several things (class Puppy not being public, method getName() not being public, etc...).
    Now,
    if you change the Puppy class so that the necessary bits are public, re-compile Puppy and then Dog it will work.
    When you subsequently go back to Puppy and remove the added public access modifiers and re-compile JUST the Puppy class and try running Dog IT WILL STILL WORK AS IF EVERYTHING IN THE PUPPY CLASS WERE PUBLIC.
    I don't thing this is right. If the access modifiers cannot be relied on then the whole system is flawed.
    PS: Running on W2K, the behaviour observed on JRE 1.2.2_007, 1.3.0_02 as well as on 1.4.0-beta-b65.
    Cheers
    Ales Krestan

    Thanks for the response, but I hold different views on the matter. Although performance surely is of a great importance, it should not come at the expense of consistency.
    A few more thoughts on the same:
    1/ my understanding is that it is responsibility of the class loader to decide what to do in such cases during the resolution case. Apparently the application class loader of SUN's JVM ignores it and so does the extension class loader of the same JVM.
    2/ surprisingly (or rather expectedly) when attempting to load both classes (with the dodged version of Puppy) using the system class loader the JVM throws java.lang.IllegalAccessError.
    3) the same trick cannot be done with an interface. If you try to dodge an interface using the same principle and try to load it using the application class loader JVM will refuse to run (or load) the class that uses the dodged interface.
    4/ the class loader DOES other things, so why not to check the access modifiers as well. It should check if the class can be instantiated, for example. See the section 2.17.3 Linking: Verification, Preparation, and Resolution of the JVM specification.

  • Access modifiers

    I dint understood the below question properly, please help me out.......
    You want subclasses in any package to have access to members of a superclass. Which is
    the most restrictive access that accomplishes this objective?
    A. public
    B. private
    C. protected
    D. transient
    E. default access
    I want to know whether the question is relating to class access modifiers or methods and variables of the classes...

    I didnt get you, please explain the topic properly.... I think classes can have only public and default as an access modifier, is it rite??? That's right. Look at [this,|http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html] it will give you a better understanding of the topic than you'd get from me answering your question.

  • Access Modifiers, Package declaration

    I created the following two classes in the same folder as two source files:
    A.java
    package abc;
    class A{
    B.java
    package abc;
    class B extends A{
    When I tried to compile, A compiled successfully. But when compiling B, it gives an error Cannot find symbol for class A.... I think it should be visible as both class access modifiers are (default). Why do I get this error????
    By the way if package declarations are removed from both classes then they compile successfully........

    i tried a lot..... does classpath affects compilation??? can u correct dis???If we're going to make the effort to help you, you could show willing and make the effort to spell out all your words and generally make your sentences as easy to understand as possible.
    Yes, the classpath affects compilation as the link provided shows. YOU can correct this.
    >
    e:\one\>javac -classpath e:\one\cert B.java
    >
    The classpath points at directories (or JAR files) not Java source files. Read the link.

  • Old access modifiers persisting after recompile

    Hello,
    I was following the Sun Tutorials for beginners and got to the exercise about developing Card and Deck classes (http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/creating-answers.html). To see if I understood the concepts about access modifiers I tried tinkering with the supplied answers, Card.java and DisplayDeck.java.
    I did the following:
    1) In Card.java, changed the class constant, DIAMONDS to private.
    2) Recompiled Card.java.
    3) Ran DisplayDeck, which uses Card.DIAMONDS.
    I did not get a run-time error. I don't understand why. Doesn't DisplayDeck.class use the latest Card.class file? Apparently not. I tried restarting my DOS session and running again. Still no error. Does DisplayDeck.class somehow keep its own version of the Card class until you recompile DisplayDeck?
    4) Then I recompiled DisplayDeck and got a compile error. This I understand.
    Thanks.
    John

    Ontological wrote:
    Thanks. Is the Bytecode the .class file? Are you saying that when you compile class B, which uses class A, that all constants from class A are stored in the Bytecode for class B?One way to work around this is to use a static initializer. This way the values are not determined at compile time, so they can't be put into dependent classes. I don't really care for this though. I'd just rather recompile everything.
    public class Constants {
      public static final int X;
      public static final int Y;
      static {
        X = 123;
        Y = 456;
    }

  • Help with access modifiers

    Hello all, i am a programmer hobbyist, did some schooling and can do alotta stuff but acess modifiers are greek to me i don't know when and what kind to use, just wondering if some can point me to a good place to learn access modifiers and when use them.
    thanks

    http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6

  • Using Java Access bridge (Accessibility) with oracle forms 6.0 client

    I'm trying to use JAB (java Access bridge ) to capture events in oracle forms 6.0 client .
    I've a Jinitiator 1.1.8 and JRE version 1.4x
    I've configured JAB as per the installation guide . However the events don't surface in Java Monkey .
    Has anybody encountered similar issue ? what is the solution for the issue ??
    Also on one of the forums I read Jinitiator 1.3x and above is automatically recognised by Java Access bridge .
    For jinitiator version less than 1.3 manual configuration is required . however I haven;'t been able to find any on the oracle forms KB
    Also here is the excerpt from the link http://www.oracle.com/us/corporate/accessibility/faqs/index.html
    Q: Are there special steps for using Java-based applications with assistive technology?
    A: If the Oracle application is written in Java, such as JDeveloper or Oracle Forms (runtime), customers must first install the latest version of Sun's Java Access Bridge. The Java Access Bridge provides the integration with screen readers such as JAWS or SuperNova that support Java. You just download the Access Bridge and install it. Sun's AccessBridge 2.0x recognizes Oracle's JInitiator 1.3x and above so no manual configuration steps are necessary. The Access Bridge is available from: http://java.sun.com/products/accessbridge. At the time this document was written, Access Bridge 2.0.1 is the most current publicly available production release; Oracle recommends upgrading to this version. Sun's AccessBridge is bundled with Oracle Universal Installer (OUI) and can be found in the Java Runtime Engine (JRE). More information for configuring such products is in the respective product documentation, or on http://www.oracle.com/us/corporate/accessibility/products/index.html.
    Edited by: 974810 on 4 Dec, 2012 1:10 AM

    ODP.NET requires Oracle Client 9.2 or higher.
    You can find additional information about ODP.NET from the FAQ:
    http://www.oracle.com/technology/tech/windows/odpnet/faq.html
    and the ODP.NET homepage:
    http://www.oracle.com/technology/tech/windows/odpnet/index.html
    Hope that helps,
    Mark

  • Java Access Helper Jar file problem

    I just downloaded Java Access Helper zip file, and unzipped, and run the following command in UNIX
    % java -jar jaccesshelper.jar -install
    I get the following error message, and the installation stopped.
    Exception in thread "main" java.lang.NumberFormatException: Empty version string
    at java.lang.Package.isCompatibleWith(Package.java:206)
    at jaccesshelper.main.JAccessHelperApp.checkJavaVersion(JAccessHelperApp.java:1156)
    at jaccesshelper.main.JAccessHelperApp.instanceMain(JAccessHelperApp.java:159)
    at JAccessHelper.main(JAccessHelper.java:39)
    If I try to run the jar file, I get the same error message.
    Does anyone know how I can fix this?
    Thanks

    Cross-posted, to waste yours and my time...
    http://forum.java.sun.com/thread.jsp?thread=552805&forum=54&message=2704318

  • [ Java Accessibility - Problem]

    I have a problem with Java Accessibility API with C#.
    I get the handle of my Applet with Spy++ and invoke the function GetAccessibleContextFromHWND (WindowsAccessBridge.dll).
    But the result pointer is -858993460 it's impossible! Then I invoke isJavaWindow and the result is FALSE! Why? the handle that I put is right! If I get an enumeration of the opened window and invoke isJavaWindow is always False! Why?
    Code:
    IntPtr HINSTANCE= SunAPI.LoadLibrary(SunAPI.PATH_WindowsAccessBridge+SunAPI.WindowsAccessBridge);
    SunAPI.Windows_run();
    long lng;
    return SunAPI.isJavaWindow(hwnd);
    SUNAPI.cs
    public class SunAPI
    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string lpFileName);
    [DllImport("WindowsAccessBridge", CallingConvention =     CallingConvention.Cdecl)]
    public extern static void Windows_run();
    [DllImport("WindowsAccessBridge", CallingConvention =     CallingConvention.Cdecl)]CallingConvention.Cdecl)]
    public extern static bool isJavaWindow(IntPtr window);
    [DllImport("WindowsAccessBridge", CallingConvention =     CallingConvention.Cdecl)]CallingConvention.Cdecl)]
    public static extern IntPtr GetAccessibleContextFromHWND(IntPtr hwnd, out long vmID,IntPtr ac);
    [DllImport("User32.dll", SetLastError = true)]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChild, string className, string windowName);
    }

    Use FindWindow instead of FindWindowEx.
    IntPtr FindWindow(string className, string windowTitle);
    Edited by: 998634 on Apr 9, 2013 3:46 AM

Maybe you are looking for