Public class question

I want to know what is the logic behind saving only one public class in one .java file. and why public class is saved with the same name.
thanks for consideration

If you're new to a large project with many classes and your assigned to make a modification to class X then where do you find this code.
If you know that class X is in the file X.java then its easy to find.
C++ is a pain for this, IDE's like visual studio will normally follow the same rules but allows the programmer to break those rules if he wishes.
Java is stricter keeping code more consistent.

Similar Messages

  • Question about access non-public class from other package.

    Hi, everyone!
    Suppose class A and class B are in the same java file of package pkg1
    -- A.java. So, A is a public class and B is a non-public class.
    If I want to access class B from another class class C and class
    C is in package pkg2. When compiling, an error occurs indicating
    that class B is not visible to class C.
    So, If I defined serveral classes in one java file and I want to
    access every class from other package. How should I do?
    (I think in one java file, there should be only one public class and
    only the public class can be accessed from other package.)
    Thanks in advance,
    George

    So, If I defined serveral classes in one java file and
    I want to
    access every class from other package. How should I
    do? As you already seem to know, there is at most one public class allowed per source file (at least, with javac and most popular compilers). So if you want more than one public class, you will need to use more than one file...

  • Error: "Could not resolve [public class] to a component implementation

    Here's another clueless newbie question! :-(
    I define a public class "DynamicTextArea" at the top of the file, and get the compiler error message "Could not resolve <DynamicTextArea> to a component implementation" at the bottom of the same file.
    Clearly, I don't understand something very basic.
    (The code between the commenrted asterisks was originally in a separate package file, which I couldn't get either mxmlc or FlexBuilder to find, so rather than fight that issue now, I moved it into the same file.)
    Here's the file:
    <?xml version="1.0" encoding="utf-8" ?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    >
    <!--****************************************************************-->
        <mx:Script>
        <![CDATA[
      import flash.events.Event;
      import mx.controls.TextArea;
    public class DynamicTextArea extends TextArea{
        public function DynamicTextArea(){
          super();
          super.horizontalScrollPolicy = "off";
          super.verticalScrollPolicy = "off";
          this.addEventListener(Event.CHANGE, adjustHeightHandler);
        private function adjustHeightHandler(event:Event):void{
          trace("textField.getLineMetrics(0).height: " + textField.getLineMetrics(0).height);
          if(height <= textField.textHeight + textField.getLineMetrics(0).height){
            height = textField.textHeight;    
            validateNow();
        override public function set text(val:String):void{
          textField.text = val;
          validateNow();
          height = textField.textHeight;
          validateNow();
        override public function set htmlText(val:String):void{
          textField.htmlText = val;
          validateNow();
          height = textField.textHeight;
          validateNow();
        override public function set height(value:Number):void{
          if(textField == null){
            if(height <= value){
              super.height = value;
          }else{      
            var currentHeight:uint = textField.textHeight + textField.getLineMetrics(0).height;
            if (currentHeight<= super.maxHeight){
              if(textField.textHeight != textField.getLineMetrics(0).height){
                super.height = currentHeight;
            }else{
                super.height = super.maxHeight;        
        override public function get text():String{
            return textField.text;
        override public function get htmlText():String{
            return textField.htmlText;
        override public function set maxHeight(value:Number):void{
          super.maxHeight = value;
        ]]>
      </mx:Script>
    <!--****************************************************************-->
         <mx:Script>
        <![CDATA[
          import mx.controls.Alert;
          private var str:String = "This text will be long enough to trigger " +
            "the TextArea to increase its height.";
          private var htmlStr:String = "This <b>text</b> will be <font color='#00FF00'>long enough</font> to trigger " +
            "the TextArea to increase its height.";
          private function setLargeText():void{
            txt1.text = str;
            txt2.text = str;
            txt3.text = str;
            txt4.text = str;
            txt5.htmlText = htmlStr;
            txt6.htmlText = htmlStr;
            txt7.htmlText = htmlStr;
            txt8.htmlText = htmlStr;
        ]]>
      </mx:Script>
      <DynamicTextArea id="txt1" width="300" height="14"/>
      <DynamicTextArea id="txt2" width="300" height="20"/>
      <DynamicTextArea id="txt3" width="300" height="28"/>
      <DynamicTextArea id="txt4" width="300" height="50"/>
      <DynamicTextArea id="txt5" width="300" height="14"/>
      <DynamicTextArea id="txt6" width="300" height="20"/>
      <DynamicTextArea id="txt7" width="300" height="28"/>
      <DynamicTextArea id="txt8" width="300" height="50"/>
      <mx:Button label="Set Large Text" click="setLargeText();"/>
    </mx:Application>
         Thanks for any insight you can provide!
    Harvey

    Gordon:
        As you've noted, there were multiple  misunderstandings.
        Some are due to references in the language which are  different from uses in pre-existing languages.
        Take "name spaces". They look like URLs but they're  not. One of the first errors I made when starting Flex was to try to browse to  http://www.adobe.com/2006/mxml. I  figured that it would have some description of the language. But it didn't. In  spite of LOOKING like a URL, it doesn't point to anything; it's really just an  arbitrary magic incantation, like "Open Sesame".
        But, then when I wanted to use my OWN namespace, I  find that it's NOT arbitrary, and does have to point to something, but it's  still not a URL. The "AHA" moment was when Michael told me that "*" means "look  in this directory for a file with the name later named in an import statement,  but not named here". And if the file was in subfolder  "X" I'd have to use "X.*", while if it were a URL I'd use slash instead of  dot, but never an asterisk.
        When the language syntax is so contrary to the  expectations of people coming from a declarative language or web programming  background, I think it is important to explicitly address the differences and  disabuse them of their preconceptions. I think the same should apply to the ways  in which ActionScript differs from ECMAScript.
        Another problem adding to my confusion is the habit  of naming variables with the names of keywords but with capitalization changes.  Not only does that set readers up for subtle "gotchas", but makes it unclear  which names are truly arbitrary, and which are required by the  compiler.
    It might be a good idea to have a convention of an  identifiable format for user variables. Many authors use names like  myButton for that purpose.
        It would also be helpful if printed text could  simulate the syntax coloring of the better editors, or at least have more  in-source comments saying exactly what each line does. (Or both)
        Another aid to understanding would be to provide a  reference to the alternative (MXML or AS) way of doing anything, whenever you  demonstrate one of the ways.
        I find that the emphasis on using FlexBuilder  distracts from a sense of what is really going on behind the scenes. E,g.: If  FlexBuilder automatically sets up the folder structure, I don't learn to do it  myself. I like to work at the code level, so when something goes wrong I don't  have to worry about what level it went wrong at.
        Also, not everyone is willing to drop $600 or $250  BEFORE they've learned whether they even like Flex. Your tutorials are, by  definition, addressed to newcomers who may well not yet have committed to the  expense of FlexBuilder. So more emphasis on using mxmlc would be nice. It would  also be helpful to discuss how to use local servers, like Tomcat, during the  development stage.
        Thanks for asking my opinion. I'm afraid that my 40  years of programming experience may make it harder for me to adapt to this new  style of programming than it would be for a kid with a tabula rasa. But, it  looks like it'll be fun once I get over the hump!
    Harvey

  • 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

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

  • Inner classes question

    Hi guys,
    I have a question to ask - when i'm writing an inner class and i want to create a new instance from it, the Eclipse forces me to use an instance of the containing class to call new.
    Is it how it's done or am i doing something wrong?
    public class A
        // Some code here
        public class B
             //Some code here
    }Trying to create an instance:
    A a = new A();
    A.B b = a.new B();

    What you have defined is "non-static" inner class.A "non-static" can only be instantiated only if we create an object of outer class.True.
    >
    There are two ways to create "inner" class object,
    1)The way you have written the codeTrue.
    2)
        public class A
    {    // Some code here    
    public void createInner()
    classB b=new ClassB();
    public classB   
    //Some code here   
    That code won't compile. Even if you corrected it so that it did compile, it doesn't really help in the OP's situation. Did you read the advice of Saish and Jos about why class 'B' probably shouldn't be public, anyway?

  • Parent Class question

    I have a panel class with a slider on it .
    pseudocode:
    public class MyJSlider extends JPanel{
    private JSlider myjslider;
    private Color mycolor;
    public Color getColor(){return mycolor;}
    the action taken by the JSlider is to set mycolor to a new Color(r,g,b);
    My question, is there away to call the class that istantiated teh MyJSlider objects paint method from the
    JSlider action performed
    Something like
    slider_B.addChangeListener(
                   new ChangeListener()
                        public void stateChanged(ChangeEvent e)
         mycolor = new Color(R,G,slider_B.getValue());
    // super.paint() ????????

    If it's an inner class like that, it has access to the outer class's fields and final instance variables.
    You can access those methods implicitly.
    But you typically don't call paint() directly, you call repaint(), which issues a call to the GUI to repaint itself. (Although maybe it's different in Swing, I don't know.)
    When you post code please wrap it in &#91;code] &#91;/code] tags so it's easy to read.

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

  • Tutorial Q&E : Implementing Nested Classes, Question 2

    //1.3
    Taken from http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-answers.html
    import java.util.*;
    public class Problem {
    public static void main(String[] args) {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
    public void run() {
    System.out.println("Exiting.");
    timer.cancel();
    5000);
    System.out.println("In 5 seconds this application will exit. ");
    Question 2: The program Problem.java (above) doesn't compile. What do you need to do to make it compile? Why?
    Answer 2: Add final in front of the declaration of the timer variable. A nested class declared within a method has access to any final, local variables in scope.
    Could somebody please elaborate on this answer for me? I don't really feel it gives enough information for me to understand fully the "why?" part.
    Thanks
    Mark

    Hi,
    the problem is that the instace of the nested class is still existing after the execution of the method has been finished. But how should it have access to a variable which doesn't exists anymore?
    The only way to solve this problem is to declare the variable as final. Because then the value of the variable is known when the instance of the nested class is created an can be copied. Then at each place in the nested class where the variable is used, the copy is used instead. This is only valid because the value of the variable cannot be changed after the creation of the nested class' instance.
    Andre

  • Public class ArrayEx extends Array

    Hi, I'm very bad at OO programming, but I'm trying to learn.
    I want to add some functions to my Arrays, like checking if
    arrays contain a value (indexOf can be equal to 0, which is false,
    though actually I'm used to the loose data typing of as2, so this
    may not be quite true. Bear with me though, I want to learn how to
    extend a class). So I'm trying to write a class that extends the
    basic Array class.
    I am confused about the constructor, I want to mimic the
    behaviour of the Array class but I'm not sure if I need to write
    functions for each method of Array. Since my ArrayEx extends the
    Array class it should inherit the array functions right? So it
    should already have .pop() and .push() ext. defined? How should I
    write my constructor to store the data the same way as the Array
    class does though?
    Is there somewhere I can look at the internal Array class to
    figure out how it does it?
    What I have written so far appears at the bottom of the
    message. I include questions as comments.
    I hope someone can help me out. I'm sorry if I'm asking stuff
    that seems obvious. Thanks for your time.
    Jon

    I've found the solution to my second set of problems and
    since I chose to trouble you all with the question I thought I'd
    post the answer.
    First problem, I had declared the ArrayEx class as dynamic
    but not as public. Should read;
    dynamic public class ArrayEx extends Array{
    Second problem. An empty constructor function, by default,
    calls the parent constructor function with no arguements. Since I
    wanted to construct my new array class like the default array class
    i had to add some code to handle that.
    So here is the working class;

  • Public class and the source filename

    May be I'm asking a silly question, but why the name of the source file needs to match with the public class's name?
    If the rule is that only one public class is allowed per source file, then the compiler can simply flag the error and quit.
    Any reasons behind this, other than for the ease of compilation?

    I refer you to the Java Language Spec:
    When packages are stored in a file system (�7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
    - The type is referred to by code in other compilation units of the package in which the type is declared.
    - The type is declared public (and therefore is potentially accessible from code in other packages).
    This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

  • 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 the name of our source file should be same as the 'public class'  name

    Hi all,
    I am very new in java and have a question in my mind.
    I read somewhere , our souce file name should be same as public class in that file.
    but i don't know the reason for this.
    Can anybody help me out with this .
    Thanks,

    HMRPanchal wrote:
    Thanks,
    Can you give me some link or documents from where I can go through this article.
    because I am not clear with what you are saying( makefiles , automatic recompilation etc).
    I am a new in Java .The fact that you don't have to worry about those things is what makes it A Good Thing.

  • From abstract class to public class

    I am developing a editor base application...wondering that how to cancel the abstract class and put all the abstract class methods into the public class..?? thanks

    Is this a C++ question? If so, you should post it in the C++ forum. If it is a Java question, post in the Java forum.
    In either case, please make your question more specific. It sounds like all you have to do is copy the functions from the abstract class to the derived class, remove the dependency on the abstract class, and delete the abstract class from the source code. Presumably that is not what you are asking.

  • Really Basic OO Class Question...

    heres the complete code for my applet...As i understand it this should make a "Car" class then should be generating a "car" object with the constructors marked...then i just use the g.drawstring to output this...but i get a nasty error message. Its something really simple, but its completely vexed me...thanks in advance.
    import java.applet.*;
    import java.awt.*;
    public class Traffclass extends Applet {
         public void init() {
         public class Car {
              public int length, width;
              public Color carColor;
              public Car() {  //constructor?
                   length = 7;
                   width = 5;
                   carColor = new Color(200,10,60);
         private Car car = null;
         public void run() {
              car = new Car();
              repaint();
         public class Trafficlight {
              public boolean greenlight = true;
         public void paint(Graphics g) {
              g.drawString(""+car.length, 50, 60 );
         //     g.fillRect(car);
    }

    As stated the problem is solved now, but heres the error message in question...
    Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
            at Traffclass.paint(Traffclass.java:39)
            at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
            at sun.awt.RepaintArea.paint(RepaintArea.java:224)
            at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
            at java.awt.Component.dispatchEventImpl(Component.java:4031)
            at java.awt.Container.dispatchEventImpl(Container.java:2024)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    grantedIt wasn't a compiler message (what i am used to) so it threw me a bit.

Maybe you are looking for