Package.Class extends Package.Class ??

Is there any way I can make a class in a package extend another class in the same package://---- File: JrcCode1.java
package jrc;
public class JrcCode1 {
  public JrcCode1() {
    System.out.println("JrcCode1");
//---- File: JrcCode2.java
package jrc;
public class JrcCode2 extends JrcCode1 {     //cannot resolve symbol, class JrcCode1
  public JrcCode2() {
    super();
    System.out.println("JrcCode2");
}Thanks,
James

The current directory is not automatically in the classpath.
You have to set it up that way. That may be your problemI have tried doing this, and it's still the same! The first code compiles but the second code fails:
javac -sourcepath . -classpath . JrcCode1.java
javac -sourcepath . -classpath . JrcCode2.java
Try extending jrc.JrcCode1. It might work, but i didnt test it outI have tried this, and it still fails:
JrcCode2.java:3: cannot resolve symbol
symbol : class JrcCode1
location: package jrc
public class JrcCode2 extends jrc.JrcCode1 {
Any other ideas?
Thanks alot!
James

Similar Messages

  • How to extend a class in same package

    I have a class called LoginBean.java which extends the class ConnectDB.java
    this both files have a statement both the classes are under the directory pmtools.
    and both are included in package pmtools.
    (they both have statement "package pmtools; " at top)
    when i am trying to compile LoginBean.java, it is giving me following error,
    LoginBean.java:7: cannot resolve symbol
    symbol : class ConnectDB
    location: class pmtools.LoginBean
    public class LoginBean extends ConnectDB
    ^
    LoginBean.java:59: cannot resolve symbol
    symbol : variable dbConn
    location: class pmtools.LoginBean
    stmt = dbConn.createStatement();
    ^
    2 errors

    did you compile the other class already? donnow if ithahahaha!!!!!
    ok include the import statement
    import pmtools.ConnectDB;
    in the second class and than compile..

  • How to extend a class from super package?

    Say I have a dir a\
    in dir a\ there is a dir b\
    in b\ there is a class called DerivedClass
    in a\ there is a class called ExtendedClass
    how do I extend ExtendedClass from DerivedClass?

    package a.b;
    import a.ExtendedClass;
    public class DerivedClass extends ExtendedClass{
        //define class members
    This is interesting. But the question is, how does java know where is package b??     By the classpath variable - the classpath is set to one directory above 'a'. When you say
         a.ExtendedClass, since the classpath is set to the immediate parent of a, it searches the child directories
         for a directory called 'a' and upon finding it, searches for a .class file 'ExtendedClass'.
         Similarly when you say a.b.DerivedClass, the search begins in the parent directory for a directory called a and then
         a directory 'b' inside it on finding which it searches for DerivedClass.class
    Alternatively you could have defined DerivedClass to be in package 'b'.     
         package b; //note the difference. Its b and not a.b
         import a.ExtendedClass;
         public class DerivedClass extends ExtendedClass{
             //define class members
         }in which case, you should set the classpath to
    1. a's parent directory
    2. a itself
    The parent directory cp is still required to locate a.ExtendedClass
    The fully qualified name of DerivedClass is b.DerivedClass
    Thus if #1 alone were present, since 'b' is not directly inside the parent directory,
    b.DerivedClass would never be found
    Hence the #2 is required-the search should start from the directory 'a' (as directory 'b' is inside 'a').
    therefore, a package is a directory.No, package is a very java specific thing and though logically package names should match directory names, they
    arent the same.
    cheers,
    ram.

  • Implemenet/Extend interface/class in default package

    Filename: DeaultInterface.java
    public interface DefaultInterface {
        // Abstract Methods...
    Filename: ConcreteClass.java
    package com.company;
    import DefaultInterface;
    public class ConcreteClass implements DefaultInterface {
        // Implementation of Abstract Methods...
    }When I compile above java code it gives error "cannot find symbol. symbol: class DefaultInterface".
    Can anyone explain why can't we implement the interface/extend the class in default package(no package)?
    Edited by: 974531 on Dec 2, 2012 11:07 PM

    >
    When I compile above java code it gives error "cannot find symbol. symbol: class DefaultInterface".
    Can anyone explain why can't we implement the interface/extend the class in default package(no package)?
    >
    You CAN implement the interface defined in the default package.
    What you CANNOT do is import it. And that is because the Java Language Specification specifies that named types can only be referenced by their simple name if they are imported and must otherwise be referenced by their fully qualified name.
    See the 7.5 Import Declarations in the Java Language Specification - http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html
    >
    An import declaration allows a named type or a static member to be referred to by a simple name (§6.2) that consists of a single identifier.
    Without the use of an appropriate import declaration, the only way to refer to a type declared in another package, or a static member of another type, is to use a fully qualified name (§6.7).
    A type in an unnamed package (§7.4.2) has no canonical name, so the requirement for a canonical name in every kind of import declaration implies that (a) types in an unnamed package cannot be imported, and (b) static members of types in an unnamed package cannot be imported. As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time error on any attempt to import a type (or static member thereof) in an unnamed package.
    >
    So you can't reference that type by importing it because you can't import a type that doesn't have a canonical nmae. And you can't just use the simple name because, as the first statement above says you have to import it to use the simple name.
    When you use the simple name of that type without an import the simple name would refer to a class IN your 'com.company' named package.

  • Can we initiate a class without extending or importing that class or packag

    Can we invoke a class
    class dog
    public static void main(String args[])
    Animal a = new Aniamal();
    like this without extending or importing the package belongs to animal.

    Can we invoke a class
    class dog
    public static void main(String args[])
    Animal a = new Aniamal();
    like this without extending or importing the package
    belongs to animal.give it the package location
    class dog
      public static void main(String args[])
        org.mypackage.Animal a = new org.mypackage.Animal();
    }

  • How do I make a batch file if the .class file uses a foreign package?

    I am trying to make an MS-DOS batch file using the bytecode file from the Java source file, called AddFields.java. This program uses the package BreezySwing; which is not standard with the JDK. I had to download it seperately. I will come back to this batch file later.
    But first, in order to prove the concept, I created a Java file called Soap.java in JCreator. It is a very simple GUI program that uses the javax.swing package; which does come with the JDK. The JDK is currently stored in the following directory: C:\Program Files\Java\jdk1.6.0_07. I have the PATH environment variable set to the 'bin' folder of the JDK. I believe that it is important that this variable stay this way because C:\Program Files\Java\jdk1.6.0_07\bin is where the file 'java.exe' and 'javac.exe' are stored. Here is my batch file so far for Soap:
    @echo off
    cd \acorn
    set path=C:\Program Files\Java\jdk1.6.0_07\bin
    set classpath=.
    java Soap
    pause
    Before I ran this file, I compiled Soap.java in my IDE and then ran it successfully. Then I moved the .class file to the directory C:\acorn. I put NOTHING ELSE in this folder. then I told the computer where to find the file 'java.exe' which I know is needed for execution of the .class file. I put the above text in Notepad and then saved it as Soap.bat onto my desktop. When I double click on it, the command prompt comes up in a little green box for a few seconds, and then the GUI opens and says "It Works!". Now that I know the concept of batch files, I tried creating another one that used the BreezySwing package.
    After I installed my JDK, I installed BreezySwing and TerminalIO which are two foreign packages that make building code much easier. I downloaded the .zip file from Lambert and Osborne called BreezySwingAndTerminalIO.zip. I extracted the files to the 'bin' folder of my JDK. Once I did this, and set the PATH environment variable to the 'bin' folder of my JDK, all BreezySwing and TerminalIO programs that I made worked. Now I wanted to make a batch file from the program AddFields.java. It is a GUI program that imports two packages, the traditional GUI javax.swing package and the foreign package BreezySwing. The user enters two numbers in two DoubleField objects and then selects one of four buttons; one for each arithmetic operation (add, subtract, multiply, or divide). Then the program displays the solution in a third DoubleField object. This program both compiles and runs successfully in JCreator. So, next I moved the .class file from the MyProjects folder that JCreator uses to C:\acorn. I put nothing else in this folder. The file Soap.class was still in there, but I did not think it would matter. Then I created the batch file:
    @echo off
    cd \acorn
    set path=C:\Program Files\Java\jdk1.6.0_07\bin
    set classpath=.
    java AddFields
    pause
    As you can see, it is exactly the same as the one for Soap. I made this file in Notepad and called it AddFields.bat. Upon double clicking on the file, I got this error message from command prompt:
    Exception in thread "main" java.lang.NoClassDefFoundError: BreezySwing/GBFrame
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
    4)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    Caused by: java.lang.ClassNotFoundException: BreezySwing.GBFrame
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    ... 12 more
    Press any key to continue . . .
    I know that most of this makes no sense; but that it only means that it cannot find the class BreezySwing or GBFrame (which AddFields extends). Notice, however that it does not give an error for javax.swing. If I change the "set path..." command to anything other than the 'bin' folder of my JDK, I get this error:
    'java' is not recognized as an internal or external command,
    operable program or batch file.
    Press any key to continue . . .
    I know this means that the computer cannot find the file 'java.exe' which I believe holds all of the java.x.y.z style packages (native packages); but not BreezySwing or any other foreign packages. Remember, I do not get this error for any of the native Java packages. I decided to compare the java.x.y.z packages with BreezySwing:
    I see that all of the native packages are not actually visible in the JDK's bin folder. I think that they are all stored in one of the .exe files in there because there are no .class files in the JDK's bin folder.
    However, BreezySwing is different, there is no such file called "BreezySwing.exe"; there are just about 20 .class files all with names like "GBFrame.class", and "GBActionListener.class". As a last effort, I moved all of these .class files directly into the bin folder (they were originally in a seperate folder called BreezySwingAndTerminalIO). This did nothing; even with all of the files in the same folder as java.exe.
    So my question is: What do I need to do to get the BreezySwing package recognized on my computer? Is there possibly a download for a file called "BreezySwing.exe" somewhere that would be similar to "java.exe" and contain all of the BreezySwing packages?

    There is a lot of detail in your posts. I won't properly quote everything you put (too laborious). Instead I'll just put your words inside quotes (").
    "..there are some things about the interface that I do not like."
    Like +what?+ This is not a help desk, and I would appreciate you participating in this discussion by providing details of what it is about the 'interface' of webstart that you 'do not like'. They are probably misunderstandings on your part.
    "Some of the .jar files I made were so dangerously corrupt, that I had to restart my computer before I could delete them."
    Corrupt?! I have never once had the Java tools produce a corrupt Jar. OTOH, the 'cannot delete' problem might relate to the JRE gaining a file lock on the archive at run-time. If the file lock persisted after ending the app., it suggests that the JRE was not properly shut down. This is a bug in the code and should be fixed. Deploying as .class files will only 'hide' the problem (from casual inspection - though the Task Manager should show the orphaned 'java' process).
    "I then turned to batch files for their simple structure and portability (I managed to successfully transport a java.util containing batch file from my computer to another). This was what I did:
    - I created a folder called Task
    - Then I copied three things into this folder: 1. The file "java.exe" from my JDK. 2. The program's .class file (Count.class). and 3. The original batch file.
    - Then I moved the folder from a removable disk to the second computer's C drive (C:\Task).
    - Last, I changed the code in the batch file...:"
    That is the +funniest+ thing I've heard on the forums in the last 72 hours. You say that is easy?! Some points.
    - editing batch files is not scalable to 100+ machines, let alone 10000+.
    - The fact that Java worked on the target machine was because it was +already installed.+ Dragging the 'java.exe' onto a Windows PC which has no Java will not magically make it 'Java enabled'.
    And speaking of Java on the client machine. Webstart has in-built mechanisms to ensure that the end user has the minimum required Java version to run the app. - we can also use the [deployJava.js|http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#deplToolkit] on the original web page, to check for minimum Java before it puts the link to download/install the app. - if the user does not have the required Java, the script should guide them through installing it.
    Those nice features in deployJava.js are available to applets and apps. launched using webstart, but they are not available for (plain) Jar's or loose class files. So if 'ensuring the user has Java' is one of the requirements for your launch, you are barking up the wrong tree by deploying loose class files.
    Note also that if you abandon webstart, but have your app. set up to work from a Jar, the installation process would be similar to above (though it would not need a .bat file, or editing it). This basic strategy is one way that I provide [Appleteer (as a downloadable ZIP archive)|http://pscode.org/appleteer/#download]. Though I side-step your part 1 by putting the stuff into a Jar with the path Appleteer/ - when the user expands the ZIP, the parts of the app. are already in the Appleteer directory.
    Appleteer is also provided as a webstart launched application (and as an applet). Either of those are 'easier' to use than the downloadable ZIP, but I thought I would provide it in case the end user wants to save it to disk and transport the app. to a machine with no internet connection, but with Java (why they would be testing applets on a PC with no internet connection, I am not sure - but the option is there).
    "I know that .jar and .exe files are out because I always get errors and I do not like their interfaces. "
    What on earth are you talking about? Once the app. is on-screen, the end user would not be able to distinguish between
    1) A Jar launched using a manifest.
    2) A Jar launched using webstart.
    3) Loose class files.
    Your fixation on .bat files sounds much like the adage that 'If the only tool you have is a hammer, every job starts to look like a nail'.
    Get over them, will you? +Using .bat files is not a practical way to provide a Java app. to the end user+ (and launching an app. from a .bat looks quite crappy and 'second hand' to +this+ user).
    Edit 1:
    The instructions for running Appleteer as a Jar are further up the page, in the [Running Appleteer: Application|http://pscode.org/appleteer/#application] section.
    Edited by: AndrewThompson64 on May 19, 2009 12:06 PM

  • Error creating instance of class from same package

    When I try to create an instance of a class that is in the same package, my IDE indicates that the constructor can not be found. Can anyone tell me what is wrong? Thanks. Below are the codes for both classes:
    package com.practice;
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;
    public class WebProject extends Applet{
         public void init(){
                    // The following line is where the IDE indicates there is an error
              UserInterface gui = new UserInterface();
         } // end init()
         public void start(){
         } // end start()
         public void stop(){
         } // end stop()
         public void destroy(){
         } // end destory()
    } // end class
    package com.practice;
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;
    public class UserInterface extends Applet{
         JPanel menuPanel = new JPanel();
         JPanel contentPanel = new JPanel();
         JPanel savePanel = new JPanel();
         ImageIcon saveIcon = new ImageIcon("workspace/images/toolbarButtongraphics/general/Save24");
         JButton saveButton = new JButton("Save", saveIcon);
         public UserInterface(){
              savePanel.add(saveButton);
              setLayout(new BorderLayout());
              add(menuPanel, BorderLayout.NORTH);
              add(contentPanel, BorderLayout.CENTER);
              add(savePanel, BorderLayout.SOUTH);
    } // end UserInterface class

    Thanks for the explanation and example. At first, I didn't understand what you were getting at, but after reading "Using Top-Level Containers" and "How to Use Root Panes" java tutorials it made much more sense. Unfortunately, the books I've read up to this point, did not cover those topics at all. The books simply stated that the first step in creating a Swing gui was to extend the JFrame, or JApplet, or etc.
    Unfortunately, my original problem persists. I continue to get compile-time errors such as:
    TestUserInterface.java:5: cannot find symbol
    symbol: class UserInterface
    location: class projects.web.TestUserInterface
                          UserInterface ui = new UserInterface(); Anyone know why?
    Both the classes are in the same named packaged. Below is my code:
    package projects.web;
    import java.awt.*;
    import javax.swing.*;
    public class UserInterface extends JFrame{
         JPanel menuPanel = new JPanel();
         JPanel contentPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         JButton save = new JButton("Save");
         JButton addFiles = new JButton("Add");
         public UserInterface(){
         super("File Upload");
         setSize(500, 500);
         menuPanel.add(addFiles);
         selectionPanel.add(save);
         setLayout(new BorderLayout());
         add(menuPanel, BorderLayout.NORTH);
         add(contentPanel, BorderLayout.CENTER);
         add(selectionPanel, BorderLayout.SOUTH);
         } // end constructor
    } // end UserInterface class
    package projects.web;
    public class TestUserInterface{
         public static void main(String[] args){
              UserInterface ui = new UserInterface();
    } // end TestUserInterface class

  • Servlet cannot invoke package classes

    I have two class which is authenticateController and userAuthentication store in authencation package with path WEB-INF/class/authentication/.
    My jvm is unable compile authenticateController in authentication directory but it is not problem in path WEB-INF/class/.
    authenticateController.java
    package authentication;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import authentication.*;
    public class authenticateController extends HttpServlet {
         //Initialize global variables
         public void init() throws ServletException {
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              doPost(request,response);   
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              //RequestDispatcher dispatcher = request.getRequestDispatcher("userAuthentication");
              //dispatcher.forward(request,response);     
              String usrnme = request.getParameter("usrnme");
              String password = request.getParameter("password");
              userAuthentication obj = new userAuthentication(usrnme, password);
              if(obj.getResult()) {
                   HttpSession session = request.getSession();
                   session.setAttribute("authenticateUser",usrnme);
                   response.sendRedirect("/developmentLine/userId/authentication/queryresult.jsp");
              else {
                   response.sendRedirect("/developmentLine/userId/authentication/login.jsp");
         //Clean up resources
             public void destroy() {
    }Any problem in my code?

    ok, this is compile error msg. I am using notepad and window cmd to compile. I able compile in classes directory (/WEB-INF/classes/) but once i move it into authentication subdirectory (/WEB-INF/class/authentication/), the authenticateController occur error msg as below.
    C:\WebJsp\servletlibrary\WEB-INF\classes\authentication>javac authenticateController.java
    authenticateController.java:28: cannot find symbol
    symbol  : class userAuthentication
    location: class authentication.authenticateController
                    userAuthentication obj = new userAuthentication(usrnme, password
                    ^
    authenticateController.java:28: cannot find symbol
    symbol  : class userAuthentication
    location: class authentication.authenticateController
                    userAuthentication obj = new userAuthentication(usrnme, password
                                                 ^
    2 errors
    C:\WebJsp\servletlibrary\WEB-INF\classes\authentication>This is the userAuthentication.java
    package authentication;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Hashtable;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import javax.naming.*;
    public class userAuthentication{
         private int totalResults;
         public userAuthentication(String usrnme, String password) {
              Hashtable env = new Hashtable();          
              String adminName = "MyCompany\\"+usrnme;
              String adminPassword = password;
              String ldapURL = "ldap://LDAPSERVER";
              //Access the keystore, this is where the Root CA public key cert was installed
              //Could also do this via the command line option java -Djavax.net.ssl.trustStore....
              //No need to specifiy the keystore password for read operations
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL,ldapURL);
              try {
                   // Create the initial directory context
                   DirContext ctx = new InitialLdapContext(env,null);
                   //Create the search controls           
                   SearchControls searchCtls = new SearchControls();
                   //Specify the attributes to return
                   String returnedAtts[]={"sn","givenName","mail","sAMAccountName","userPrincipalName","mailNickname","streetAddress"};
                   searchCtls.setReturningAttributes(returnedAtts);
                   //Specify the search scope
                   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                   //specify the LDAP search filter
                   //mailNickname and sAMAccountName is same, but sAMAccountName is Old NT 4.0 logon name and it may confuse to CN attribute.
                   String searchFilter = "(&(objectClass=user)(mailNickname="+usrnme+"))";
                   //Specify the Base for the search
                   String searchBase = "DC=MyCompany,DC=com,DC=my";
                   //initialize counter to total the results
                   totalResults = 0;
                   // Search for objects using the filter
                   NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
                   //Loop through the search results
                   while (answer.hasMoreElements()) {
                            SearchResult sr = (SearchResult)answer.next();
                        totalResults++;
                   ctx.close();
              catch (NamingException e) {
                   System.err.println("Problem searching directory: " + e);
         public boolean getResult() {
              if(totalResults == 0)
                   return false;
              else
                   return true;
    }Edited by: webster on Nov 17, 2008 4:49 PM
    Edited by: webster on Nov 17, 2008 4:51 PM

  • Package and class path

    for two yrs i am trying to get package right but no result
    i am using window 98
    i have my jdk in d:\jdk1.2\bin; and this works fine if i do not try to use package;somtimes it works well half way with package!
    suppose i want to create a package called rubberband and put classes in it
    i created a folder called rubberband in d:\ and then
    package rubberband;
    import java.awt.*;
    public class RubberbandTest extends Frame{}
    class RubberbandTestPanel {}
    class Colorchoice{}
    this is one unit
    and there are other classes
    package rubberband;
    import java.awt.*;
    abstract class Rubberband {}
    package rubberband;
    import java.awt.*;
    class RubberbandPanel extends Rubberband {}
    and so on
    i opened executive.bat and added to class path as follows:
    path:d:\rubberband\bin;before the already existing d:\jdk1.2\bin;
    then when i come to compile and run the program i have problems
    like:class so and so not found
    please help please step by step tell me what to do

    Another sample might answer your "different location" question.
    Suppose program YourProg in package yourPkg located in directory C:\javaprogs needs to access a class file ExtraClass in package extraPkg in directory C:\differentDir.
    1) Of course the source file must exist in file
    C:\javaprogs\yourPkg\YourProg.java
    and
    C:\differentDir\extraPkg\ExtraClass.class must exist.
    2) Inside the YourProg source, you must import ExtraClass:
    import extraPkg.ExtraClass;
    3) To compile YourProg, you must include location of extraPkg.ExtraClass in the classpath (or the compiler will complain about the inport line above):
    (a -- from C:\javaprogs directory): javac -classpath C:\differentDir yourPkg\YourProg.java
    (b -- from any directory): javac -classpath C:\javaprogs;C:\differentDir yourPkg\YourProg.java
    4) To run YourProg (assuming it contains a main method), you must include all locations in classpath:
    (a -- from C:\javaprogs directory): java -classpath .;C:\differentDir yourPkg.YourProg
    (b -- from any directory): java -classpath C:\javaprogs;C:\differentDir yourPkg.YourProg
    If you get a NoClassDefFoundError, that means that the java was run without the proper location included in the classpath passed to the -classpath argument. The -classpath argument should be ';'-separated and contain no spaces (so if a long directory name contains space you should enclose in double quotes, as this example:
    java -cp "C:\Program Files\somedir;C:\anotherdir" NameOfAClass

  • How to import a class from a package at the same level

    Hello friends,
    i have a class as Plaf.java
    as
    package org.vaibhav.swing.plaf;
    import java.awt.*;
    import javax.swing.*;
    public class Plaf {
    other code
    }as you see, this is in org.vaibhav.swing.plaf package.
    I have one more class as
    package org.vaibhav.swing.frames;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class StartFrame extends JFrame implements ActionListener {
    other code
    }and this class is in package org.vaibhav.swing.frames
    Please hlp me how to use the class Plaf in StartFrame.java. Rather what import statement should i use in StartFrame.java.
    please help.
    thank you
    Message was edited by:
    vaibhavpingle

    but it then gives me this error
    StartFrame.java:11: package org.vaibhav.swing.plaf
    does not exist
    import org.vaibhav.swing.plaf.*;
    Have you first compiled Plaf.java and saved it in this directory strucuture
    /org/vaibhav/swing/plaf/
    And also have you set your classpath to the parent directory of org folder.
    Message was edited by:
    qUesT_foR_knOwLeDge

  • How to refer to a protected class outside the enclosing package

    Hi all,
    At the page 357 of the book Java Language Specification(Second Edition), when saying about checking accessibility of Type and Method, they concern Let C be the class containing the method invovation T.m, if T is in a different package than C, and T is protected then T is accessible if and only if C is a subclass of T. I just wonder how to refer a protected type outside the package it declared.
    For example,
    package test;
    public class test {
    static protected class protectedTest {
    public void foo() {..}
    in another package
    import test.*;
    class subtest extends test.protectedTest {  <- error
    Anyone can give me an example showing an invocation directly to foo() declared in class test.protectedTest ? The invocation should appear outside package test.
    Thanks,
    Ha Chau

    The protected inner class would be accesible only within a class which extends test, where you could either use or extend it as in:
    class subtest extends test {
        private static class sub2 extends protectedTest {
               }

  • How to comunicate two class in the same package

    I HAVE SET MY CLASSPATH as /home/shadab/program/java/MyPack in CLASSPATH environment variable.
    below is a super class java file Protection.java
    I also compiled it successfully using javac Protection.java
    package MyPack;
    public class Protection {
    int n = 1;
    private int n_pri = 2;
    protected int n_pro = 3;
    public int n_pub = 4;
    public Protection() {
    System.out.println("base constructor ");
    System.out.println("n = " + n);
    System.out.println("n_pri = " + n_pri);
    System.out.println("n_pro = " + n_pro);
    System.out.println("n_pub = " + n_pub);
    Below is subclass of superclass
    package Mypack;
    class Derived extends Protection {
    Derived() {
    System.out.println("Derived constructor ");
    System.out.println("n = " +n);
    // System.out.println("n_pri = " + n_pri);
    System.out.println("n_pro = " + n_pro);
    System.out.println("n_pub = " + n_pub);
    while i compiled subclass
    javac Derived.java
    following error occured
    Derived.java:3: cannot find symbol
    symbol: class Protection
    class Derived extends Protection {
    ^
    Derived.java:8: cannot find symbol
    symbol : variable n
    location: class Mypack.Derived
    System.out.println("n = " +n);
    ^
    Derived.java:11: cannot find symbol
    symbol : variable n_pro
    location: class Mypack.Derived
    System.out.println("n_pro = " + n_pro);
    ^
    Derived.java:12: cannot find symbol
    symbol : variable n_pub
    location: class Mypack.Derived
    System.out.println("n_pub = " + n_pub);
    PLEASE HELP ME TO SOLVE THIS PROBLEM ..

    1. To post code, use the code tags -- [code]Your Code[/code]will display asYour CodeOr use the code button above the editing area and paste your code between the {code}{code} tags it generates.
    2. Read this page:
    [http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html]
    3. I advise that you don't use the CLASSPATH environment variable. Instead, use the -classpath or -cp flag when compiling/running.
    4. The package root must be available on the classpath. Since your classes are in the package MyPack and in the folder /home/shadab/program/java/MyPack, that means that /home/shadab/program/java must be on the classpath.
    db

  • How to use classes of packages in flex mx:Script/ or mxml/

    Hi.I am just learning Flex using Flex Builder 3 facing one problem,
    Suppose I declare one package with name alert.as
    package
    import mx.controls.Alert;
    public class alert
    public function alertBtn()
    Alert("Hello btn 1");
    Now in want to use the function in mxml that I declared in a package.
    <mx:Button label="btn1" click="alertBtn();"  />
    I have few questions
    1)How to Import the class alert.as in <mx:Script> and where should i store the file alert.as in the directory folder of flex?
    2)How to call the function alertBtn() when btn1 is clicked.
    Thanks so much!
    Regards
    Ankur

    Hi Greg.I think I was not able to clear my problem properly.Let me try this time again.
    What I wanted to do was that in the below written code I have the full access of the id=panel1 in the  script tag .This works properly.
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
    import flash.display.Sprite;
    import mx.core.UIComponent;
    private function addChildToPanel():void {
    var circle:Sprite = new Sprite();
    circle.graphics.beginFill(0xFFCC00);
    circle.graphics.drawCircle(0, 0, 20);
    var c:UIComponent = new UIComponent();
    c.addChild(circle);
    panel1.addChild(c);
    ]]></mx:Script>
    <mx:Panel id="panel1" height="100" width="100"/>
    <mx:Button id="myButton" label="Click Me" click="addChildToPanel();"/>
    </mx:Application>
    This above functionality when I tried to do using class Outside the code ,its not working !
    Here is with the package:-
    But suppose I make One package 
    package
    import flash.display.Sprite;
    import mx.core.UIComponent;
    class getPanel extends Sprite
    public function addChildToPanel():void {
    var circle:Sprite = new Sprite();
    circle.graphics.beginFill(0xFFCC00);
    circle.graphics.drawCircle(0, 0, 20);
    var c:UIComponent = new UIComponent();
    c.addChild(circle);
    panel1.addChild(c);
              }//class
                        }//package
    Now in MXML
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
    import getPanel;
    ]]></mx:Script>
    <mx:Panel id="panel1" height="100" width="100"/>
    <mx:Button id="myButton" label="Click Me" click="getPanel.addChildToPanel();"/>
    </mx:Application>
    So My problem is that this code doesnt do anything.
    Neither the addChild function is working in it ,Nor the Panel1 is accessible here.
    Can u pls help me here.
    Thanks
    Ankur

  • //package classes;

    i have used the code below,,and my application is working fine...but when i removed the comments from the package ling..the 404 error is coming..i have compiled the servlet with package line uncommented..whats the reason?
    //package classes;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    public class CookieLoginServlet extends HttpServlet {
         public void doGet(HttpServletRequest request ,HttpServletResponse response)
         throws ServletException,IOException {
              sendLoginForm(response,false);
              System.out.println("inside get");
         public void doPost(HttpServletRequest request,HttpServletResponse response)
         throws ServletException ,IOException {
              String userName=request.getParameter("userName");
              String password=request.getParameter("password");
              if(login(userName,password)){
    Cookie c1=new Cookie("userName",userName);
    Cookie c2=new Cookie("password",password);
    response.addCookie(c1);
    response.addCookie(c2);
    response.setContentType("text/html");
    PrintWriter out =response.getWriter();
    // response.sendRedirect does not work here.
    // use a Meta tag to redirect to ContentServlet
    out.println("<META HTTP-EQUIV=Refresh CONTENT=0;URL=ContentServlet>");
              }else{
                   sendLoginForm(response,true);
         private void sendLoginForm(HttpServletResponse response,boolean withErrorMessage)
         throws ServletException ,IOException {
              response.setContentType("text/html");
              PrintWriter out=response.getWriter();
              out.println("<html>");
              out.println("<head>");
              out.println("<title>Login</title>");
              out.println("<body>");
              out.println("<center>");
              if(withErrorMessage){
                   out.println("login failed .plz try again<br>");
                   out.println("if u think you have entered the correct user name "+
                        "and password,the cookie setting in your browser might be off " +
                        "<br>Click<a href=InfoPage.html>here</a> for information ");
              out.println("<br>");
              out.println("<br><h2>please enter your username and password</h2>");
              out.println("<br>");
              out.println("<br><form method=POST>");
              out.println("<table>");
              out.println("<tr>");
              out.println("<td>userName:</td>");
              out.println("<td><input type=text name=userName></td>");
              out.println("</tr>");
              out.println("<tr>");
              out.println("<td>password:</td>");
              out.println("<td><input type=password name=password></td>");
              out.println("</tr>");
              out.println("<tr>");
              out.println("<td><input type=submit value=submit></td>");
              out.println("</table>");
              out.println("</form>");
              out.println("</center");
              out.println("</body>");
              out.println("</html>");
         public static boolean login(String userName,String password){
              try{
                   Class.forName("sun.jdbdc.odbc.JdbcOdbcDriver");
                   Connection con =DriverManager.getConnection("jdbc:odbc:JavaWeb");
                   Statement s=con.createStatement();
                   String sql="SELECT UserName FROM users" +
                   "WHERE UserName='"+fixSqlFieldValue(userName)+ "'"+
                   "AND password='"+fixSqlFieldValue(password)+"'";
                   ResultSet rs= s.executeQuery(sql);
                   if(rs.next()){
                        rs.close();
                   s.close();
                   return true;
                   }else
                   {     rs.close();
                   s.close();
                   con.close();
              }catch(ClassNotFoundException e){
                   System.out.println(e.toString());
         catch (SQLException e) {
         System.out.println(e.toString());
         catch (Exception e) {
         System.out.println(e.toString());
         return false;
         public static String encodeHtmlTag(String tag){
              if(tag==null)
              return null;
              int length=tag.length();
              StringBuffer encodeTag=new StringBuffer(2*length);
              for(int i=0; i<length; i++) {
              char c=tag.charAt(i);
              if(c=='<')
              encodeTag.append("<");
              else if(c=='>')
              encodeTag.append(">");
              else if(c=='&')
              encodeTag.append("&");
              else if(c=='"')
              encodeTag.append(""");
              else if(c==' ')
              encodeTag.append(" ");
              else
              encodeTag.append(c);
              return encodeTag.toString();
         public static String fixSqlFieldValue(String value) {
              if (value==null)
              return null;
              int length = value.length();
              StringBuffer fixedValue = new StringBuffer((int) (length* 1.1));
              for(int i=0; i<length; i++) {
              char c = value.charAt(i);
              if(c=='\'')
              fixedValue.append("''");
              else
              fixedValue.append(c);
              return fixedValue.toString();
    }

    It means you didn't deploy the servlet properly.
    Put the package back - all your Java classes should go into packages. All the time. The only exception is when you're writing a quick knock-off to test something that you'll run on the command line and rarely use again.
    No surprise - the code you've written is certainly terrible. HTML to the output stream - ever heard of JSP?
    SQL code in a servlet - ever hear of Data Access Objects?
    Layering apps makes them easier to test, debug, maintain, and understand.
    What servlet/JSP engine are you using? Tomcat? If so, Tomcat requires that you use packages.
    Where did you put this beauty of a servlet? Better not be /ROOT. Create a directory under /webapps for your app and deploy it there.
    What URL did you use to invoke the servlet? I'll bet that's wrong, too.
    Lots to correct here.
    %

  • To access a package, the calling class must reside in the root/parent direc

    My goal was to be able to access my package from anywhere within the
    high level root folder (d:\zJava). But it seems the invoking class MUST
    RESIDE IN THE TOP LEVEL PARENT DIRECTORY of the package. Was Java
    designed to behave this way?
    D:\zJava\zsamples\com\zswingpackage1>     <-- packages successfully compiled here
         swing_optgrp_eg1.{class/java}
              package com.zswingpackage1;
              public class swing_optgrp_eg1 extends JFrame implements ItemListener {
    D:\zJava\zsamples\com> <-- classes residing here could NOT successfully                    access the package 'com.zswingpackage1'. The third                    level subfolder is 'com'.
         package_test4.java
              /* Following import stmt. causing RUN-TIME error "Exception in thread     "main" java.lang.NoClassDefFoundError: com/zswingpackage1/swing_optgrp_eg1". */
              import com.zswingpackage1;
         Package_Test4.class          
         /* Unsuccessful remedies:
         i) D:\zJava\zsamples\com>java Package_Test4
                   -classpath .;d:\zJava\zsamples\com\zswingpackage1
                   -classpath .;d:\zJava\zsamples\com
                   -classpath .;d:\zJava\zsamples (also used in compile)
                   -classpath .;d:\zJava
         ii) ran from the root/parent directory of the package d:\zJava\zsamples),with and without classpath i.e.
              D:\zJava\zsamples>java com\Package_Test4 [-classpath .;d:\zJava\zsamples]
         iii) ran from the top level directory (d:\zJava), with and without classpath i.e.
              D:\zJava>java zsamples\com\Package_Test4 [-classpath .;d:\zJava\zsamples]
         Possible causes:
              - maybe the above behaviours are by design i.e. the calling class/program CANNOT be stored within the package hierarchy?
    D:\zJava\zsamples\net> <-- classes residing here could NOT successfully access the package 'com.zswingpackage1'. The third level subfolder is 'net'.
         package-test6.java
              /* Following import stmt. causing RUN-TIME error "Exception in thread "main" java.lang.NoClassDefFoundError: com/zswingpackage1/swing_optgrp_eg1". */
              import com.zswingpackage1;
         Package_Test6.class
         /* Unsuccessful remedies:
         i) D:\zJava\zsamples\net>java Package_Test6
                   -classpath .;d:\zJava\zsamples\com\zswingpackage1
                   -classpath .;d:\zJava\zsamples\com
                   -classpath .;d:\zJava\zsamples (also used in compile)
                   -classpath .;d:\zJava
         ii) ran from the root/parent directory of the package (d:\zJava\zsamples), with and without classpath i.e.
              D:\zJava\zsamples>java net\Package_Test6 [-classpath .;d:\zJava\zsamples]
         iii) ran from the top level directory (d:\zJava), with and without classpath i.e.
              D:\zJava>java zsamples\net\Package_Test6 [-classpath .;d:\zJava\zsamples]
         Possible causes:
              - maybe the above behaviours are by design i.e. the calling class/program MUST be stored in the parent folder of the package hierarchy?
    **D:\zJava\zsamples>     <-- classes residing here SUCCESSFULLY accessed package 'com.zswingpackage1'. NO -classpath parms. were necessary!
    D:\zJava\ <-- classes residing here could NOT successfully access the package 'com.zswingpackage1'. Similar scenarios as above.
    D:\zJavaB\ <-- classes residing here could NOT successfully access the package 'com.zswingpackage1'. I purposely created another folder with the 'B' suffix. Similar scenarios as above.
    My PC configuration:
         java version "1.4.0_01"
         Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_01-b03)
         Java HotSpot(TM) Client VM (build 1.4.0_01-b03, mixed mode)
         JRun 4 (Build 47304)
         WinNT 4.0 SP5
         IE 5.50
         CLASSPATH=.;D:\jakarta-tomcat-3.3.1\lib\common\servlet.jar;
              C:\JRun4\servers\default\default-ear\default-war\WEB-INF\classes
         JAVA_HOME=C:\j2sdk1.4.0_01
         Path=C:\j2sdk1.4.0_01\bin;C:\WINNT\system32;C:\WINNT;
              C:\Program Files\Network Associates\PGPNT;C:\Program Files\MTS;d:\MSSQL7\BINN
    Thank you so much for your expertise.

    Hello,
    I think that you use the import-declarations incorrectly.
    Your code says:
    import com.zswingpackage1;
    ... The meaning of the above declaration is the following: Import the class "zswingpackage1" from the package "com". The compiler cannot find that class, but it is probably never asked to find it in your code, so it won't report an error.
    If you want to import the whole package use the following declaration instead:
    import com.zswingpackage1.*;
    ... That means: import all classes from from the package "com.zswingpackage1".
    You can also import just the classes needed, e.g.:
    import com.zswingpackage1.swing_optgrp_eg1;
    ... I hope that does the job.
    S&oslash;ren

Maybe you are looking for

  • Getting error when using the "/parameter" switch in command line run

    Has anyone experienced this problem before? My report queries over 100,000 records from a view. When the report is run from the command line every thing works fine. But when I add a condition using a "parameter", although the report still runs fine f

  • Privacy settings on photoshop express app

    I downloaded the photoshop express app to my iphone.  I initially chose not to allow it to 'work' from my camera roll.  Now, I realize I do need that and need to find how to allow this.  The directions are to go the privacy settings and change.  Howe

  • Can I buy the removable side panel for mac Pro

    Does Apple sell side panel for the MacPro (early 2009) ?

  • I'm scared help me please

    I need to change from btbroadband talk (anytime call package) to anytime call package on my landline number, the reason being I have a homehub2 which apparently is not compatible with btsport so I need a hub3 or hub4 or the new hub5 which I understan

  • DBCA step 12 hangs in 74% after ora-28010

    Hi guys, I'm running an oracle10g database EE on a UNIX SOLARIS 10 SPARC box, and trying to recreate a database from a DBCA template. When I do all steps, the process claims for an ora-28010 error when it completes 74% and after that DBCA never ends.