Why do we need public classes?

I read that a public class is more visible than a default (non-public) class as the latter is merely "package-visible". However, it appears that even if a class (c in package p) is not declared to be public, it can still be accessed by:
1) p.c
2) import p.c
So what is the use of declaring a class to be public? Why can't we just write:
class c {...}
every time for every class without the modifier public.
Can someone show me an example that illustrates the difference between a public class and a default class?

I read that a public class is more visible than a
default (non-public) class as the latter is merely
"package-visible". However, it appears that even if a
class (c in package p) is not declared to be public,
it can still be accessed by:
1) p.c
2) import p.c
How does that appear so?
Trying to do it the compiler says that "p.c is not public in p; cannot be accessed from outside package" and does not generate a class file.

Similar Messages

  • Why files with no public classes have no naming restrictions ?

    As i know a file with a public class ,uch have the same name as the class name but the files with no public classes have no naming restrictions and then how we can access these classes ?

    but the files with no public classes have no naming restrictions and then how we can access these classes ?You can access a class in a files with no public classes have no naming restrictions by just creating their object.
    Here is the code you can run.
    File: NonPublic.java
    * @(#)NonPublic.java
    * @author Gagan Ichake
    * @version 1.00 2009/1/15
    class NotAsFileName{
         void baz()
              System.out.println("I am in NonPublic class.");
    }File: AccessNonPublic.java
    * @(#)AccessNonPublic.java
    * @author Gagan Ichake
    * @version 1.00 2009/1/15
    public class AccessNonPublic {
            public static void main(String []arg)
              NotAsFileName nafn = new NotAsFileName();
              nafn.baz();
    }Edited by: Ggn on Jan 15, 2009 10:53 PM

  • Why do I need a class or interface?

    Why am I getting this error?
    "ReportQueryBuilder.java": Error #: 202 : 'class' or 'interface' expected at line 484, column 12
    This line is causing the error...what am I missing?
    public Connection openCon(String sUid, String sPwd) throws ReportQueryBuilderException
            //connection
            Connection dbCon = "";
         }

    "throws ReportQueryBuilderException"
    You probably throw an uncaught exception from the parent class ... in whatever ReportQueryBuilderException is, change it to 'throws Exception' and debug it yourself if an Exception is ever created with a System.out.println or two

  • Why do we need Persistent Classes ?

    Dear OO Gurus,
    I just finished the chapter on "Persistent Objects" in "ABAP Objects - ABAP Programming in SAP NW by Horst Keller".
    I could really appreciate its utility though. Googled a bit, read a few blogs on SCN but still the utility remains blurred.
    I would like to know what is the advantage of Persistence Classes over Open SQL.
    BR,
    Suhas

    I would like to know what is the advantage of Persistence Classes over Open SQL.
    Let's first start with what SAP says about the [persistence service|http://help.sap.com/saphelp_nw70ehp2/helpdata/en/f5/a36828bc6911d4b2e80050dadfb92b/frameset.htm]:
    The Persistence Service lets the ABAP programmer work with relational database data in an object-oriented way.
    So we're talking here about an [ORM|http://en.wikipedia.org/wiki/Object-relational_mapping] framework. I.e. the persistent storage of data is realized in SAP via a [relational database|http://en.wikipedia.org/wiki/Relational_database], where the data model is not object oriented. Let's say that you have created a class sales order and want to store and retrieve sales order objects (i.e. specific instances of this class). If you have a relational database, you have to model a corresponding schema for representing your sales order class and then "handcode" the translation from database tables into sales order objects and vice versa.
    Now imagine a world where you have a nice ORM, that does the work for you. E.g. look at web frameworks like [grails|http://www.grails.org/] making heavy use of [convention over configuration|http://en.wikipedia.org/wiki/Convention_over_configuration], which allow you to easily generate database representations from your objects (without tons of coding/effort!). Essentially you can start off with your class definitions, define some attributes and the framework (ORM) will automatically generate the corresponding database tables for you.
    Contrast that with SAP (see online help on [mapping assistant for persistence classes|http://help.sap.com/saphelp_nw70ehp2/helpdata/en/d9/b84508bc9411d4b2e80050dadfb92b/frameset.htm]):
    You may have to create new database tables, database views, or structures for the object model in the ABAP Dictionary. At present the system does not perform this function automatically.
    So in general the ORM is supposed to make the developer's life easier by providing a framework for translating objects into (relational) database tables. However, sometimes the automatic translation/generation along with the default access methods is not optimal and that's where you actually go back to code your own SQL statements for doing the database-to-object conversions and vice versa. So the SAP persistence classes still use OpenSQL under the hood, but in some cases (e.g. mass processing), you might want to tune the used SQL statements yourself...
    I apologize for the long excursion, but in the end my view on persistence classes is quite simple: Use them if they make your life more simple and your coding less complex, without causing any bigger performance hit - otherwise stick to handcoded SQL statements... (long live [KISS|http://en.wikipedia.org/wiki/KISS_principle]!)
    Cheers, harald

  • Why it is necessary that public class name should  same as filename in java

    hi,
    why it is necessary that public class name should same as filename in java.
    As I know that it is a convention, but I want the information why this convention is made.
    thanx.

    user13445117 wrote:
    but suppose if i am creating a java file with default access modifire then we do not need to save the file name as a class name.So, your question is "Why does the rule about top-level classes being in a file of the same name apply +only+ to public classes"?
    If it were applied to all classes, then we could never have two top-level classes in the same file. Doing that is generally not a good idea, but it might be useful from time to time. EJP already told you why it applies to public classes, and, since these are the most common by far, it's a fair compromise that it apply to them but not to other classes.
    Was this the reason the original designers did it that way 15 or so years ago? Don't know, don't care, but it's one plausible explanation. Maybe it was just a balance between simplicity and clarity on the one hand, and flexibility on the other.
    It's certainly not something I can see caring that much about, unless you're doing an in-depth history on Java, or writing an in-depth treatise on computer language and compiler theory.

  • Why is U51 blocking individual class files not in jars but U45 accepted them?

    Let me answer the "why do you need individual class files?" question first. We have a rather large applet based application with a current client-side minimum jar download size of 1.8 MB. If we put ALL of our class files into jars, that size will probably double. Most users only use a small portion of the class files for their particular tasks. Which of the class files they use depends upon the tasks they perform. Having ALL users download ALL the classes, albeit compressed in jars, is extremely time consuming and a major problem after application updates due to the large number of users and the network load it would cause.
    Jar file manifest:
    Permissions: all-permissions
    Codebase: *
    Application-Name: MyApplication
    Application-Library-Allowable-Codebase: *
    Caller-Allowable-Codebase: *
    Trusted-Library: true
    We have 11 directories with one containing the applet and main client application code. The other 10 directories contain class files relating to the various sub-applications in the system. The system has a third-party runtime jar file, too.
    We have a private network and servers for our business so the exposure is small. This is a screen-scraping, reformattring application that does no real data processing so doesn't need the same security as a true data processing application. Since we are not open to the Internet and of limited security risk, we chose to keep a more simplified structure.
    This all worked under 1.7.0_45. I read the security guide and it was my understanding that these attributes in the manifest would also work for U51. Apparently not. Looking at the guides, now, it appears they have been changed sometime last year regarding mixed-code to mean jars with certificates and jars without certificates. The support for individual class files appears to have been removed. If this is true, then there should have been a beta of the U51 code because the rules seem to have been changed since the last release or there is a new bug.

    This is exactly my same problem. My app (and applet) is about 5 MB if I consider all the classes and libraries used by the app. (I mean 5MB is the size of the jar file). I can't ask customers to download 5 MB every time they want to access the program.
    We need java ask code signing for the principal applet but then we must have the possibility to run single class files as needed.
    Help us all please.
    Thanks Paolo

  • Why do we need a Self Reference "me" to use the components of a class

    Hi
    I am not clear why do we need a self reference variable "me" to call the components of its own class? when it can be accessed directly as in the following examples?
    In my first example below i can call the method display_name directly without creating a reference object or instance of the class within the class.
    In the second example i am using the self refernce Write me->name to access the component of a class.
    My question is why do we need "me" when i can use the components directly as shown in my first example.
    CLASS egocentric DEFINITION.
      PUBLIC SECTION.
        DATA:
         name(10) TYPE c READ-ONLY.
        METHODS set_name.
        METHODS display_name.
    ENDCLASS.                    "egocentric DEFINITION
    *       CLASS egocentric IMPLEMENTATION
    CLASS egocentric IMPLEMENTATION.
      METHOD set_name.
        MOVE 'Abap Objects' TO name.
        CALL method display_name.
      ENDMETHOD.                    "write_name
      METHOD display_name.
        write: name.
      ENDMETHOD.                    "display_name
    ENDCLASS.                    "egocentric IMPLEMENTATION
    *Global Data
    DATA oref TYPE REF TO egocentric.
    START-OF-SELECTION.
      CREATE OBJECT oref.
      CALL METHOD oref->set_name.
    CLASS egocentric DEFINITION.
            PUBLIC SECTION.
                DATA:
                 name(10) TYPE c VALUE u2018Instructoru2019
    READ-ONLY.
                 METHODS write_name.
    ENDCLASS.
    CLASS egocentric IMPLEMENTATION.
            METHOD write_name.
                WRITE me->name.
            ENDMETHOD.
    ENDCLASS.
    *Global Data
    DATA oref TYPE REF TO egocentric.
    START-OF-SELECTION.
            CREATE OBJECT oref.
            CALL METHOD oref->write_name.

    You can go WIKI and search with ABAP Objects.
    Or do the same in 'advanced search'  and select a search area. You are bound to find something.
    Or this link perhaps:
    [abap objects|http://help.sap.com/saphelp_nw70/helpdata/EN/ce/b518b6513611d194a50000e8353423/content.htm]

  • Why is the name of java file is same as public class?

    hello friends
    why we need to assign same name to .java file as the name of public class in .java file? while its not necessary for the class having no modifier?

    This question has been asked several times. Serch the forum.
    x

  • Why do we need the @EJB annotation at the class level?

    Why do we need the @EJB annotation at the class level?
    Eg: Why do we need the first piece of code, when the second code seems much simpler .
    *1.*
    @Stateful
    @EJB(name="ejb/TradeLocalNm",
    beanInterface=TradeLocal.class)
    public class TradeClientBean implements TradeClientRemote {
    *2.*
    @Stateful
    public class TradeClientBean implements TradeClientRemote {
    @EJB private TradeLocal trd;
    }

    I think it is possible to do it in an aggregated level however you need to define your distribution rules in order to get the desired result, you need also to consider that if distribution rules changes and the value after promotional planning returns the same value, it is possible that detailed level are not realigned to the new distribution rule (e.g. regarding another ratio).
    Maybe this is one of several causes.
    Regards,
    Carlos

  • Why File Name is Same Name as The Public Class Name

    Hi Friends,
    What is the reason for Naming the File Name is puvlic class name??
    thanks in advance.

    konstkaras wrote:
    What could be reason to give it other name?
    It's as much better as we have less distinct names.
    When I was a schoolboy, I programmed Turbo Pascal. Each program there had a name (declared in file's beginning). The name was never used, but: it has no such restriction of length (as MS-DOS file names had) and it could clash with other identifiers described in code.
    So why those names should be distinct?Java was invented after MSDOS was obsolete, so 8.3 limits were not a consideration.
    Java is designed for larger programs than were attempted in the MSDOS era, so supports compilation of programs which are created from many source files. Turbo Pascal 4 also supported separate compilation units, and did use the name you mention for exactly that purpose, but I can't remember how it dealt with dependencies between compilation units.
    Having the public class' name and package as component in the source file path and the class file path simplifies the dependency problem between the compilation units - all the compiler has to do to determine whether the foo.bar.Baz class needs updating is to look whether foo/bar/Baz.class exists, and if it is less recently modified than foo/bar/Baz.java.

  • Abstract classes: Why do they need constructors?

    As we cannot instantiate an abstract class. Why does an abstract class need a constructor?.can anyone please help me out..Thnq in advance
    OBELISK

    import java.util.*;
    import static java.lang.System.out;
    interface LineItem{
        public int getCost();
    abstract class AbstractLineItem implements LineItem{
      protected String name;
      AbstractLineItem(String name){
         this.name = name;
      public String toString(){
        return this.name+" "+getCost();
      public abstract int getCost();
    class ProductItem extends AbstractLineItem{
       private int quantity, peritem;
       ProductItem(String name, int quantity, int peritem){
         super(quantity+" "+name);
         this.quantity = quantity;
         this.peritem = peritem;
       public int getCost(){
         return this.quantity*this.peritem;
    class FlatFeeItem extends AbstractLineItem{
       private int fee;
       FlatFeeItem(String name, int fee){
         super(name);
         this.fee = fee;
       public int getCost(){
         return this.fee;
    public class Test{
      public static void main(String ... args){
        List<LineItem> items = new ArrayList<LineItem>();
        items.add(new ProductItem("Banana",6,1));
        items.add(new FlatFeeItem("Some boring thing or another",35));
        items.add(new ProductItem("Kiwi",3,3));
        for(LineItem item : items)
          out.println(item);
    }

  • Why we need Java Class in c++ pof Serialization

    Hi,
    I'm really confused why we need java class which implements PortableObject to support complex objects of c++. If we are not using any queries or entry processors in the application can't we keep the object as serialized byte format and can't we retrieve in from the c++ deserialization.
    Please share your thoughts if there's a way if we can skip any Java implementation.
    regards,
    Sura

    feel both are doing same work. Also can anyone tell me what is teh difference between Serilization and Exgternalization.If you need someone to tell you the difference, (a) how can you possibly 'feel both are doing the same work'? and (b) why don't you look it up in the Javadoc?
    It's not a secret.

  • Only one public class - why???

    Hi
    I have come across this statement many places -
    "There can be only one Top-Level 'public' class in
    a java source file which should have same name as that
    of the fore mentioned class."
    I know that the compiler searches for the class
    with same name as that of the file that is passed to
    the compiler.I am also aware that a Java source compiles
    smoothly with One or None Top-Level 'public' class,
    but I fail to comprehend this -
    Why can there be only one TOP-LEVEL 'public' class
    in a Java Source file?
    The importance of 'TOP-LEVEL' is as important as
    any thing else, as you yourself check that a Nested
    class within an Enclosing class can be 'public' along
    with someother Top-Level 'public' class in the program
    compiles smoothly unlike having TWO Top-Level 'public'
    classes in same file.
    I have found no reason supporting this statement in any
    of the refernces I have checked out.Ppl I have asked told
    me that it is so coz Java Spec say so.
    Is there an better answer to my question?
    Thanx in advance, appretiate it.
    Regards
    Pradeepto

    I have found no reason supporting this statement in
    in any
    of the refernces I have checked out.Ppl I have asked
    told
    me that it is so coz Java Spec say so.I can tell you that anybody who says its because the Java spec says so, is wrong - the Java spec does not say so.
    It is a limitation of Sun's javac compiler, which many other compilers exhibit as well. I don't know the full formal reasoning behind it (and would be interested in knowing if you find a good answer), but I assume it simply has to do with finding classes without having to load everything on your classpath.
    Whether other compilers are purposely acting the same way as javac, or whether it is some sort of performance optimisation that most vendors feel is worthwhile, I couldn't say.
    I don't see what you're saying about top-level and nested classes. Although you can declare a public nested class inside a non-public top-level class, the nested class is not actually publicly visible, by virue of its enclosing class not being publicly visible.

  • Why public class name should be same as the java file name

    Hi,
    I would like to know, why public class name should be same as the its java file name. Iam in the process of finding the answer to this question. Can someone help me out in finding the explanation.
    Thanks in advance,
    Manoj

    This is a requirement of the Java reference compiler released by Sun. I have used compilers that did not require this, but most seem to follow the reference compiler (which is a very good idea). I am NOT sure if this is specified in the Java Language Specification. Some of the other regulars who are more familiar with the JLS than I may be able to tell you.
    ? {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Why do we need material specification for transfering results to class char.

    Hi,
    Can you guys tell me why do we need to create material specification if we want to transfer quality inspection results to a batch class?
    Basically I have done the following:
    -Create Class Characteristic
    -Assign the Class Characteristic to a batch class
    -Link Class Char.  to MIC
    -Assign MIC to an Inspection Plan
    -Post GR, batch and inspection lot are created automatically
    -Record Results for inspection Lot
    -Make UD for Inspection Lot
    The result is not transferred to batch class, then I create material specification with the MIC assigned, the results can be transferred. But why?
    Best regards
    Danny

    Hello Danny,
    This is a standard program, which checks for this indicator at the time of inspection lot completion.
    F1- help gives satisfactory explanation
    Batch Valuation Possible Without Specification
    Use
    If you set this indicator, a link between the master inspection
    characteristics and the class characteristics for the batch class must exist
    when an inspection lot is created, for batch valuation to occur when the usage
    decision or inspection point valuation is made. A link within the material
    specification is not required.
    If you do not set this indicator, batch valuation only occurs when the
    usage decision or inspection point valuation is made, if a link using the
    material specification exists between the master inspection characteristics and
    the class characteristics for the batch class. In this way, you can control on a
    material-dependent basis whether the batch characteristics are valuated based on
    the inspection results.
    Amol.
    Message was edited by: Amol Manave : Main purpose is you can control whether Batch characteristics should be valuated based on results or not for particular material. If you set this indicator then batch characteristics will be valuated for all materials and in opposite case Batch characteristics will be valuated for only materials for which Material Specification exists.

Maybe you are looking for