Class Foo

public class Foo {
int i;
static String s;
void imethod(){
static void smethod() {
Let f be an instance of Foo. Which of the following statements are correct?
System.out.println(f.i);
System.out.println(f.s);
f.imethod();
f.smethod();
System.out.println(Foo.i);
System.out.println(Foo.s);
Foo.imethod();
Foo.smethod();
Could someone explain how this works without giving away the answer?

anything declared as "static" in class are the class variable. for your example , static String s and static void smethod(). In order to use them, u had to use the class to call them Foo.i and Foo.smethod
So how about those not in static? yr int i, and void imethod() ?
Ans : only when u make instance of Foo class, then u can only use those objects to call those non-static variable and method. As follows:
Foo f = new foo;
f.i = 15;
f.smethod;
We should not directly access the i like above. That the rules of object-orientated programming, where we hide those details from people, so we will declared it as "private" and use instance method to set the value of i.

Similar Messages

  • How to access a class file outside the package?

    created a two java files Counter.java and TestCounter.java as shown below:
    public class Counter
         public void print()
              System.out.println("counter");
    package foo;
    public class TestCounter
         public static void main(String args[])
              Counter c = new Counter();
              c.print();
    Both these files are stored under "D:\Test". I first compiled Counter.java and got Counter.class which resides in folder "D:\Test"
    when i compile TestCounter.java i got the following error message:
    D:\Test>javac -classpath "d:\Test" -d "d:\Test" TestCounter.java
    TestCounter.java:6: cannot find symbol
    symbol : class Counter
    location: class foo.TestCounter
    Counter c = new Counter();
    ^
    TestCounter.java:6: cannot find symbol
    symbol : class Counter
    location: class foo.TestCounter
    Counter c = new Counter();
    ^
    2 errors
    what could be the problem. Is it possible to access a class file outside the package?

    ya that's fine..if we have two java files where both resides in the same package works fine or two java files which donot have a package statement also works fine. But my doubt is, i have a Counter.class which does not reside in a package and i have a TestCounter.class which resides in a package "foo", in such a scenario, how do i tell to the compiler that "Counter.class resides in such a path, please look at that and give me TestCounter.class". i cannot use import statement to import Counter.class in TestCounter.java because i donot have a package for Counter.java.

  • How to reference a class without using the new keyword

    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();

    quedogf94 wrote:
    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();No.
    Using new does not erase anything. There's nothing to erase. It's brand new. It creates a new instance, and whatever that constructor puts in there, is there. If you then change the contents of that instance, and you want to see them, you have to have maintained a reference to it somewhere, and access that instance's state through that reference.
    As already stated, you seem to be confused between class and instance, at the very least.
    Run this. Study the output carefully. Make sure you understand why you see what you do. Then, if you're still confused, try to rephrase your question in a way that makes some sense based on what you've observed.
    (And not that accessing a class (static) member through a reference, like foo1.getNumFoos() is syntactically legal, but is bad form, since it looks like you're accessing an instance (non-static) member. I do it here just for demonstration purposes.)
    public class Foo {
      private static int numFoos; // class variable
      private int x; // instance varaible
      public Foo(int x) {
        this.x = x;
        numFoos++;
      // class method
      public static int getNumFoos() {
        return numFoos;
      // instance method 
      public int getX() {
        return x;
      public static void main (String[] args) {
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ();
        Foo foo1 = new Foo(42);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ();
        Foo foo2 = new Foo(666);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ("foo2.numFoos is " + foo2.getNumFoos ());
        System.out.println ("foo2.x is " + foo2.getX ());
        System.out.println ();
    }

  • Best practice for class and constructors

    I'm writing a small utility class that has a private member that is a List. I'm troubled when I think about where this List should be created - in the declaration of the reference or in the default constructor - thus having all other constructors call the default.
    Should I have:
    public Class Foo() {
        private List myList = new ArrayList();
      public Foo() {
      public Foo(String myFoo) {
      public Foo(String[] myFoo) {
      // more methods....
    }or would it be better to code it as:
    public Class Foo() {
        private List myList;
      public Foo() {
        myList = new ArrayList();
      public Foo(String myFoo) {
        foo();
       // other stuff
      public Foo(String[] myFoo) {
        foo();
       // other stuff
      // more methods....
    }In the first option, I know from putting a watch on myList that it stays undefined until any one of the constructors in called. This would seem to me to be the best approach as it doesn't require future additional constructors to have to be written to specifically call the default constructor just to get the ArrayList created. What's typically done in this situation? Which one is considered "good form" or is there a better way?

    I'm writing a small utility class that has a private
    member that is a List. I'm troubled when I think
    about where this List should be created - in the
    declaration of the reference or in the default
    constructor - thus having all other constructors call
    the default.It's not done this way - you have to call this().
    I think the better solution is to have the creation and initialization of the List in the most specific constructor, and have the default call that:
    public class Foo
        private List myList;
        public Foo()
            this(Collections.EMPTY_LIST);
        public Foo(List newList)
            this.myList = new ArrayList(newList);
    }%

  • How to remove the rule or class function in CS5

    i need to know how to remove the rule or class function in CS5  at the bottom of the screen there are two options for formating HTML and Css when i click the HTML it only allows me to change the bold or italics or link something but when i click CSS it allows me to format how i want the paragraph aligned and the text size and font when i click on lets say changing the font size a box comes up asking me to name a rule so it applies it to everything else i type i want to know how to stop tht like edit everything on my own and if i use CS5 here will it be compatible with CS4 or CS3 at my skool plzz help ive been frustrated with this

    If I use CS5 here will it be compatible with CS4 or CS3 at my skool plzz help ive been frustrated with this
    Code is code.   It doesn't matter which product you use.
    i need to know how to remove the rule or class function in CS5
    You can't.  DW encourages you to use good coding methods, which means using CSS classes and to keep content (HTML) separate from styles (CSS).  For example, if you change font-size on p tags like so:
         p {font-size: 38px}
    Every paragraph will have 38px sized text.
    If you want to apply a special style to just a portion of your text, you must define a CSS class name like so:
    .foo {
    font-size: 38px;
    color: red;
    HTML:
    <p>This is normal paragraph text <span class="foo"> And this is very big and red.</span></p>
    This is normal paragraph text And this is very big and red. 
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists 
    http://alt-web.com/
    http://twitter.com/altweb
    Message was edited by: Nancy O.  -- unfortunately, this forum doesn't support Raw HTML with inline styles. You'll need to paste my code examples into your DW page to see the effect.

  • Problems with Embedded classes mapping

    Hi,
    I'm experiencing problems for table generation with the following case:
    a class declares two fields; one of them typed as a subclass of the other; both fields annotated with @Embedded; the subclass uses the annotation @AttributeOverride to avoid column names duplication.
    When the tables are generated, one of the field (the most specialized one) is simply omitted by the JPA implementation...
    To illustrate my problem, here is an example:
    @Entity
    public class Bar implements Serializable {
         @Embedded
         protected Foo foo = null;
         @Id
         @GeneratedValue(strategy=GenerationType.SEQUENCE)
         protected long id = -1;
         @Embedded
         protected SubFoo subFoo = null;
         public Bar() {
                    super();
            // getters & setters
    @Embeddable
    public class Foo implements Serializable {
         @Column
         protected String bar = null;
         @Column
         protected String foo = null;
         public Foo() {
              super();
            // getters & setters
    @Embeddable
    @AttributeOverrides({
         @AttributeOverride(name="bar", column=@Column(name="subbar")),
         @AttributeOverride(name="foo", column=@Column(name="subfoo"))
    public class SubFoo extends Foo {
         public SubFoo() {
                    super();
    }The generated table BAR contains only 3 columns: ID, FOO, BAR...
    ...and what I expect is two additionnal columns named SUBFOO & SUBBAR!
    Can someone tell me: if I definitely need to go back to school (I'm obviously not an EJB expert), or how to make it work as I expect...?
    Thanks
    -Jerome

    I found the note in the EJB specs that clearly states that my issue has no solution at this time:
    "Support for collections of embedded objects and for the polymorphism and inheritance of embeddable classes will be required in a future release of this specification."
    EJB 3.0 specs - final release - persistence, page 23, note 10 in section 2.1.5

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Nested classes and separate files in Javadoc...

    Hello. I am writing an application, and it has several .java files, and some of the classes contained therein contain nested classes, for example
    ClassOne.java
    class ClassOne
    // stuff
       class innerClassOne
          //more stuff
    }ClassTwo.java
    class ClassTwo
    // stuff
       class innerClassTwo
          //more stuff
    }What I want to do is generate documentation like the online java documentation for my app, that is, documentation that will contain ALL the classes and nested classes involved, and link everything that comes in java already to the sun online java docs.
    I've figured out the -link command for javadoc, and I can make that work, but I've run into some other snags.
    1.) Javadoc isn't finding or documenting my nested classes, despite them being marked up. Google does not wish to help.
    2.) Some classes reference other classes of mine that aren't conatined in the same .java file, but do exist in their own .java files in the dame local directory. Javadoc does not like this, and gives errors.
    3.) Running javadoc on one file at a time overwrites the old file's documentation, thus I cannot seem to get an index.html javadoc file that links to all my classes, nor can I get the classes to link to each other.
    What do I need to do to fix these?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • How to determine the Class of a static methods class?

    hi,
    is there a way to get the code below to output
    foo() called on One.class
    foo() called on Two.classthanks,
    asjf
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
    class One {
       public static final void foo() {
          System.out.println("foo() called on "/*+something.getClass()*/);
    }

    - One.class won't resolve to Two.class when the static
    method is called via the class TwoThat's because static methods are not polymorphic. They cannot be overridden. For example try this:
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
          One one = new Two();
          one.foo();
          ((Two) one).foo();
       public static void foo() {
          System.out.println("foo() called on Two");
    class One {
       public static void foo() {
          System.out.println("foo() called on One");
    }

  • How to deserialize xml with structure of abitrary nested layers of base class?

    let say i want to represent arithmetic expression using xml:
    <?xml version="1.0" encoding="utf-8" ?>
    <expr>
    <add>
    <num>10</num>
    <num>20</num>
    </add>
    </expr>
    and here is my classes to represent this:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace Test
    public abstract class Evaluable
    public abstract int Eval();
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    namespace Test
    [Serializable]
    [XmlRoot("expr")]
    public class Expr
    [XmlElement]
    public Evaluable Evaluable { get; set; }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    namespace Test
    [Serializable]
    [XmlRoot("add")]
    [XmlType("add")]
    public class Add : Evaluable
    [XmlElement]
    public List<Evaluable> Elems { get; set; }
    public override int Eval()
    return Elems.Select(e => e.Eval()).Sum();
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    namespace Test
    [Serializable]
    [XmlRoot("num")]
    [XmlType("num")]
    public class Num : Evaluable
    [XmlText]
    public int Val { get; set; }
    public override int Eval()
    return Val;
    but it doesn't work, and it's reasonable, since Serializer doesn't know any thing about the subclass. but how to make it work?
    here is my deserialization code:
    var serializer = new XmlSerializer(typeof(Expr), new[] { typeof(Add), typeof(Num) });
    Expr expr = null;
    using (var file = new StreamReader("expr.xml"))
    expr = serializer.Deserialize(file) as Expr;

    I think what you want is to set the XmlElement attribute on the container (Elems).
    It can be done if the deserializer can be made aware of all the potential subclasses of the base class.  It's ok to put multiple XmlElement attributes on the container to let the deserializer know about the various subclasses it can deserialize.
    I don't think there's a way to tell the XmlSerializer externally about new types.  I could be wrong.  [If someone shows me how to do that, I'd sure appreciate it!]   [WORKAROUND:  A potential workaround
    is to create a class that contains all the potential children including the class itself and serialize that.  Seems a little like cheating.]
    Here is a complete example:
    [Serializable]
    public class Foo
    [XmlAttribute( "name" )]
    public string name;
    [XmlElement( "Foo", Type = typeof( Foo ) )]
    [XmlElement( "Bar", Type = typeof( Bar ) )]
    public List<Foo> children = new List<Foo>();
    public void Dump( int level )
    ShowProperties( level );
    foreach( var f in children ) {
    f.Dump( level + 1 );
    protected virtual void ShowProperties( int level )
    Console.WriteLine( "{0}{1}", new string(' ', level * 4 ), name );
    [Serializable]
    public class Bar : Foo
    public string stuff;
    protected override void ShowProperties( int level )
    base.ShowProperties( level );
    Console.WriteLine( "{0}{1}", new string(' ', level * 4 ), stuff );
    class Program
    static void Main( string[] args )
    // <Foo name="A">
    // <Bar name="B">
    // <Foo name="D" />
    // <stuff>B's Stuff</stuff>
    // </Bar>
    // <Bar name="C">
    // <stuff>C's Stuff</stuff>
    // </Bar>
    // </Foo>
    // A
    // B
    // B's Stuff
    // D
    // C
    // C's Stuff
    Foo a = new Foo() { name = "A" };
    Bar b = new Bar() { name = "B", stuff="B's Stuff" };
    Bar c = new Bar() { name = "C", stuff="C's Stuff" };
    Foo d = new Foo() { name = "D" };
    a.children.Add( b );
    a.children.Add( c );
    b.children.Add( d );
    XmlSerializer xs = new XmlSerializer( typeof( Foo ) );
    // There:
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces( new[] { XmlQualifiedName.Empty } );
    StringBuilder sb = new StringBuilder();
    using( XmlWriter xw = XmlWriter.Create( sb, new XmlWriterSettings() {
    OmitXmlDeclaration = true,
    Indent = true
    xs.Serialize( xw, a, ns );
    Console.WriteLine( sb.ToString() );
    // And Back Again:
    using( StringReader sr = new StringReader( sb.ToString() ) )
    Foo root = (Foo)xs.Deserialize( sr );
    root.Dump( 0 );

  • JLS3: Scope of type parameter and inner class declaration

    The following code:
    class Foo<E>
      class E
        E foo()
          return this;
    }produces this error message:
    $ javac Foo.java
    Foo.java:7: incompatible types
    found   : Foo<E>.E
    required: E
          return this;
                 ^
    1 errorApparently, the type parameter E of the outer class Foo shadows the inner class declaration E. An alternative way to check is to create a new E() in this method, which results in an error message about using a type parameter where a type is expected.
    Of course this code is sick, but I would like to know where this is defined in the JLS3, since I cannot find out in which way this shadowing works. What I've found until now:
    Page 179:
    "The scope of a class' type parameter is the entire declaration of the class."
    Page 190:
    "The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, ... "
    Page 132:
    "If a type name consists of a single Identifier, then the identifier must occur in the scope of exactly one visible declaration of type with this name, or a compile time error occurs."
    Section 6.3.1 (Shadowing declarations) specifies the shadowing rules, but does not mention type parameters.
    Any help is appreciated.

    The current behaviour in eclilpse seems to be the one we get if the bug in javac is fixed as described.
    This code compiles
    public class Shadow1 {
         class Foo<E>
           class E
              E foo()
               return this;
    }but this code
            Foo<E>.E foo()
               return this;
             }shows
    Type mismatch: cannot convert from Shadow1.Foo<E>.E to Shadow1.Foo<Shadow1.Foo<E>.E>. E
    Not sure if this error message is correct.

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • Loading Classes

    Hi,
    Here is my problem. I have a directory with several classes (foo_1, foo_2, ...) which all extend a base class (foo); I want to create a vector with an instance of each class in it. The problem is I dont know what the classes will be called or even how many classes will be in the directory when I generate my vector, so I dont know to do this. Does anyone have a suggestion? =)

    File f = new File("/path");
    File[] files = f.listFiles();
    List l = new ArrayList(files.length());
    for (int cntr = 0, len = files.length(); cntr < len; cntr++)
    l.add(files[cntr]);
    That will create a List of the actual File objects. Now if you want to load the class, you would need a little more work. The path you pass uses / (or \ on windows), to separate it, so you would need something to replace / or \ with . to get the fully qualified package name, OR if you already know the fully qualified package name, do this:
    String[] fileNames = f.list(new FileNameFilter()
    public boolean accept(File dir, String name)
    // do code here to determine if file is acceptable:
    // possibly checking if file is not dir and only file...
    if (dir.isFile())
    return true;
    Now you have a list of filenames and if you use the filename filter above to block out dirs, you should only have file names (although on linux/unix you may get symbolic link names as well, not sure).
    From here you would do something like:
    List l = new ArrayList(fileNames.length());
    for (int cntr = 0, len = fileNames.length(); cntr < len; cntr++)
    l.add(Class.forName(fullyQualifiedPackageName + "." + fileNames[cntr], true, getClass().getClassLoader()).newInstance());
    I have not tested this, but it should work. Basically, the first example gets you the File objects, in case that is what you wanted. The above example gets you the list of file names as String objects, you then append that name (in the loop to do the whole dir) to the fully qualified package (how you get that is up to you, perhaps some code to get the dir name, or some other way), and you are dynamically loading it AND creating an instance of it via the Class.forName() call.
    Hope that helps.

  • Java.sql.SQLException: Cannot load JDBC driver class 'null'

    Hi,
    I am a beginner of using jdbc, i use the tomcat4.1.x, mysql3.23.54 and it's jdbc driver 2.0.14. I place the drive <in jar file> in tomcat/commons/lib and configure the server.xml, web.xml and some testing coding. But there are some error like the following:
    java.sql.SQLException: Cannot load JDBC driver class 'null'
         at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:529)
         at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:312)
         at foo.DBTest.init(DBTest.java:18)
         at org.apache.jsp.test_jsp._jspService(test_jsp.java:48)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:136)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:204)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:289)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:240)
    of course its some of the error code and there are more.
    Why I have this problems and how can I fix it? Can someone help me??
    Thanks,
    Tong
    I place my test.jsp at tomcat/webapps/DBTest and DBTest.java at tomcat/webapps/DBTest/WEB-INF/classes/foo
    additional of the tomcat/conf/server.xml
    <Resource name="TestDB" auth="Container" type="javax.sql.DataSource" description="MySQL TestDB"/>
    <ResourceParams name="TestDB">
    <parameter><name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>
    <parameter><name>maxActive</name><value>10</value></parameter>
    <parameter><name>maxIdle</name><value>1</value></parameter>
    <parameter><name>maxWait</name><value>10000</value></parameter>
    <parameter><name>username</name><value>javauser</value></parameter>
    <parameter><name>password</name><value>javadude</value></parameter>
    <parameter>
    <name>driverClassName</name>
    <value>org.gjt.mm.mysql.Driver</value>
    </parameter>
    <parameter>
    <name>url</name>
    <value>jdbc:mysql://localhost:3306/javatest?autoReconnect=true</value>
    </parameter>
    </ResourceParams>
    tomcat/webapps/DBTest/WEB-INF/web.xml :
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <description>MySQL Test App</description>
    </web-app>

    Post the part of your code that loads the driver and connects. My guess is you are using a variable for the name of the driver and the variable has not been set to anything(intially set to null).
    Thanks
    Cardwell

  • NoClassDefFoundError extending class in separate JAR

    I have a class Foo which gets called from my servlet (extends HttpServlet) class. Both Foo and the servlet class are located in WEB-INF/classes and are deployed as part of the war file. Class Foo extends class Bar, which is a different .jar file located in the /WEB-INF/lib directory of the webapp. When I attempt to create an instance of Foo, I get the following exception:
    java.lang.NoClassDefFoundError: /general/client/common/beans/Bar
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$100(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:268)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1267)
         at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
         at server.DBServlet.createFoo(DBServlet.java:236)
         at server.DBServlet.processInput(DBServlet.java:333)
         at server.DBServlet.doGet(DBServlet.java:154)
         at server.DBServlet.doPost(DBServlet.java:205)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:432)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:419)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
         at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:667)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    I'm running this on Windows, and found if I added the classpath the the jar file where the Bar class is located, that it worked fine. But my expectation is that the jar file should have been found because it is in the /WEB-INF/lib dir. There is a line the Tomcat docs that says:
    "Last, any JAR containing servlet API classes will be ignored by the classloader. All other class loaders in Tomcat 5 follow the usual delegation pattern."
    So maybe I need to do something special to load the Bar class, or there's something strange about the way the classes and jars are being loaded that I don't fully understand. I was able to instantiate the Bar class directly from w/in my servlet class, I just can't create an instance of the Foo class that is in /WEB-INF/classes along with the servlet class. So I'm not convinced that the Bar class or associated jar file isn't being loaded.
    I don't want to have to set the classpath explicitly, so I'm looking for advice on why I'm getting this exception and how best to dynamically load the classes I need.
    Thanks.
    ab.

    Thanks for hanging in there so far. Here's the specifics if you want to try to re-create this.
    I have a webapp, which contains the class DBServlet:
    package com.hm.dhca.server;
    public class DBServlet extends HttpServlet
    // Stuff
         public void processInput()
              Foo foo = new Foo();
    The webapp also contains the class Foo:
    package com.hm.dhca.common;
    import com.general.client.common.beans.Bar;
    public class Foo extends Bar
         public Foo()
              super();
              System.out.println("Foo");
    Both of the classes are located in webapps\DHCA\WEB-INF\classes...
    The Bar class is in a separate jar called HMJCommon.jar in the webapps\DHCA\WEB-INF\lib dir.
    Class Bar looks like this:
    package com.general.client.common.beans;
    public class Bar
         public Bar()
              System.out.println("Bar");
    DBServlet creates an instance of Foo as:      
    Foo foo = new Foo();
    Which throws the Exception:
    java.lang.NoClassDefFoundError: com/general/client/common/beans/Bar
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$100(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:268)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1267)
         at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
         at com.hm.dhca.server.DBServlet.processInput(DBServlet.java:236)
         at com.hm.dhca.server.DBServlet.doGet(DBServlet.java:154)
         at com.hm.dhca.server.DBServlet.doPost(DBServlet.java:205)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:432)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:419)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
         at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:667)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    Clues:
    1. All three classes exist in the locations specified above - I have checked this manually.
    2. Within DBServlet, I can create an instance of Bar. But I cannot create an instance of Foo without the exception.
    3. If I move the Foo class from package com.hm.dhca.common to package com.hm.dhca.server (same package as DBSerlvet), everything works fine.
    4. If I modify Tomcat's classpath to include the HMJCommon.jar, it works fine (as previously discussed).
    Theory:
    I have a vague theory that what is happening is that two different webappclassloaders are loading the Foo and Bar classes, for whatever reason. As a result, they can't see each other, because neither is up the hierarchy tree from the other.
    This does not explain how I can instantiate Bar from DBServlet, but not Foo.
    Hope this helps. I think I've corrected previous mistake w/ removing too much from package naming. I'm resorting to the workaround in clue #3 for the moment. But it's not the correct solution, and it's showing that I don't really understand what's going on here.

Maybe you are looking for

  • How do i send the username and password to yahoo web page through url

    how do i send the username and password to yahoo web page through url i.e as Query string so that my account in yahoo will open...

  • Editable field in alv tree output using cl_gui_alv_tree

    Hi, i need Editable field with F4 help in alv tree output using cl_gui_alv_tree. regards, Naresh

  • How to start with CDC?

    Hi, friends: I have read much online material about CDC, but I'm still confused. I knew that I can download the WTK2.2 or higher to develop the app based on the CLDC and MIDP. My question is how to start with CDC. For example, If I use JBuilder, what

  • Manually Manage Music Option Diasppeared

    I'm hoping someone can help me with a really frustrating change that seems to have happened to itunes since I started using iMatch: the option to manually manage music and videos has disappeared and been replaced by an option to manage video only. If

  • Cannot drop Mapping

    Hi, in our project there is an mapping that seems to be corrupt. We cannot open it (when the editor opens, it shows nothing). So we would like to import that map from an older MDL-file. But we also cannot drop the mapping. OWB shows an API5072 Error