Non-public methods in interface ??

Is this possible? Or must all methods (signatures) in an interface be public?
And would that mean that I cannot change the visibility modifier in implementing classes as this restricts the visibility by inheritance, which I believe is prohibited...
Thanks for any answer,
AC

Everything in an interface must be public. However, the interface itself doesn't have to be.
Yes that means that all implementing classes must have public implementing methods.
However, proxies, adapters and decorators will get you out of serious design problems if you bump into any.
Hope this helps.

Similar Messages

  • Why only public methods in interfaces?

    Howdy all,
    I'm wondering if someone can shed some light on why Java doesn't allow interfaces to declare non-public methods.
    Ideally, I'd like to do something like this:
    public Interface Foo {
      protected void setFooProperty(int);
      public int getFooProperty();
    public Interface Goo {
      protected void makeGooey(boolean);
      public boolean isGooey();
    public class A implements Foo
    public class B implements Goo
    public class C implements Foo, GooI don't see any technical reason why interfaces must be restricted to declaring public methods only, but it seems too arbitrary to have been done without reason. Any ideas?

    I don't think that is a good idea to put non-public methods in public interfaces. But I beleive that's a good idea to have protected (or friendly) interfaces to be used only in package scope. It could help a lot some projets defining a second level of data exposure of an object so that developers of that package could have more information that others users from outside the package have that are interesting to develop better algorithm that work with that data. In this way, we can defien thre levels of that access: The lower is the package user, that can see the minimum that's possible, above him we have the package developer that don't work directly with the data, but needs some deep access to it to do cool stuff, and finally we have the guy that is doing the object that deals directly with the data (and encapsulate it).
    In this way we can decouple a little the data from the algorithms that work on it, put between them an interface that standarize the access to the data in an intermediate level.
    Hope you are able to understand what I wrote (my english isn't so good!).
    RGB

  • Identifying non-public methods

    Is there any way for an object to idenify its own non-public methods (getMethods() returns only those methods that are declared public)?

    getDeclaredMethods() - I believe this might do what you want. It throws a SecurityException, but I'm not sure exactly under what circumstances! Oh, and it doesn't return methods defined on any superclasses.

  • Delegate class to access non-public methods during testing?

    In the following video, towards the end, someone asked that FlexUnit assumes functions and methods are to be public when tested.
    http://tv.adobe.com/watch/max-2008-develop/testing-your-flex-applications-by-michael-labri ola/
    The speaker replied (@ 52:25),  to use Delegate classes, which are linked in when being tested. 
    Can someone show me an example of this?  Thanks.

    Mike, thanks for the reply!
    As I am new to unit testing, things are still solidifying.  I do understand that Unit Testing, “tests the smallest functional unit of code”, which are methods and functions.  However, I incorrectly assumed that *every* method needed to be tested *directly*.   Hence, I thought all methods would have to be public.  So that would have blown encapsulation out of the water.  Now I understand from your reply, that private methods get tested indirectly from public methods.  And that seems more ideal.
    Thanks again.

  • Non public interfaces

    Non public interfaces are not permitted. But I often want to break out the methods of an interface into sub-interfaces for the sake of (at least) comprehensibility. Ultimately, only the aggregate interface is meant to be exposed, but of course, they are all exposed- Java doesn't permit non-public interfaces.
    E.G. -
    interface Foo extends interface Bar, Baz
    class DefaultFoo implements Foo
    // implementation of Bar and Baz
    of course I could have DefaultFoo just implement Bar and Baz directly, but it's not the point. The point is, I have a good reason
    to want these mini-interfaces... for the sake of comprehension. A Foo is just exactly the combination of Bar and Baz
    and elsewhere a Goo is an implementation of a Bar and Gaz, where Gaz is some other interface.
    So the utility of the interfaces lies in the conceptual cohesion of the abstraction they define, which will never be implemented
    individually, but only in different aggregates.
    What do other people do with this kind of situation?

    Yep, you can do that, but only in classes - no inner interfaces embedded in interfaces, not that that would have helped me in this case !
    I think that generally, problems with scoping and issues involving more flexibility around visibility will be addressed in 7.
    I knew interfaces can be embedded privately in classes, but not that they could be package protected. Just a feature I never had any reason to use I guess or more likely knew and just forgot!
    Sheesh!

  • IllegalAccessError when trying to create a proxy for a non-public interface

    My code proxies a class that extends JDialog. Under Java5 this works fine. However when I switch to Java6 I get a java.lang.IllegalAccessError: class javax.swing.$Proxy3 cannot access its superinterface javax.swing.TransferHandler$HasGetTransferHandler exception.
    I went through debugging my code to find out what went wrong. I created the included test code that shows the problem (and because the real codebase is much too big to include here).
    package javax.swing;
    public class SomePackageInterfaceDefiningClass {
        interface SomeInnerPackageInterface {
    package javax.swing;
    import java.lang.reflect.Proxy;
    import java.util.ArrayList;
    import java.util.Collection;
    import org.apache.commons.lang.ArrayUtils;
    public class NonPublicInterfaceProxyCreator {
        public static void main(String[] args) {
            // This works fine !
            doTest(WindowConstants.class);
            // This also ! The proxy class package is javax.swing as expected
            doTest(SomePackageInterfaceDefiningClass.SomeInnerPackageInterface.class);
            // JDialog implements the package visible interface
            // javax.swing.TransferHandler.HasGetTransferHandler
            Collection<Class<?>> jdInterfaces = new ArrayList<Class<?>>();
            for (Class<?> interfaze : JDialog.class.getInterfaces()) {
                jdInterfaces.add(interfaze);
            Collection<Class<?>> strippedJdialogInterfaces = new ArrayList<Class<?>>(
                    jdInterfaces);
            for (Class<?> interfaze : jdInterfaces) {
                if (interfaze.getName().equalsIgnoreCase(
                        "javax.swing.TransferHandler$HasGetTransferHandler")) {
                    strippedJdialogInterfaces.remove(interfaze);
            // Without the package visible interface it works !
            doTest(strippedJdialogInterfaces.toArray(new Class<?>[0]));
            // With the package visible interface it fails
            doTest(jdInterfaces.toArray(new Class<?>[0]));
        private static void doTest(Class... interfaces) {
            // Class clazz = Proxy.getProxyClass(JDialog.class.getClassLoader(),
            // interfaces);
            Class clazz = Proxy.getProxyClass(Thread.currentThread()
                    .getContextClassLoader(), interfaces);
            System.out.println("Class created = " + clazz
                    + " >>>> Implemented interfaces = "
                    + ArrayUtils.toString(clazz.getInterfaces()));
    }When I run this code under Java5 I get:
    Class created = class $Proxy0 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Class created = class javax.swing.$Proxy1 >>>> Implemented interfaces = {interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface}
    Class created = class $Proxy2 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Class created = class $Proxy2 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}Under Java6 I get:
    Class created = class $Proxy0 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Class created = class javax.swing.$Proxy1 >>>> Implemented interfaces = {interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface}
    Class created = class $Proxy2 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Exception in thread "main" java.lang.IllegalAccessError: class javax.swing.$Proxy3 cannot access its superinterface javax.swing.TransferHandler$HasGetTransferHandler
         at java.lang.reflect.Proxy.defineClass0(Native Method)
         at java.lang.reflect.Proxy.getProxyClass(Proxy.java:504)
         at javax.swing.NonPublicInterfaceProxyCreator.doTest(NonPublicInterfaceProxyCreator.java:45)
         at javax.swing.NonPublicInterfaceProxyCreator.main(NonPublicInterfaceProxyCreator.java:38)According to the documentation the interface javax.swing.TransferHandler$HasGetTransferHandler should be visible to my class as it is located in the same package, right?
    I think there must be some classloading issue when trying to access the non-public interface javax.swing.TransferHandler$HasGetTransferHandler in rt.jar.
    I can not figure out what is different between my own non-public interface and Swing's javax.swing.TransferHandler$HasGetTransferHandler.
    Any help would be appreciated.

    I don't agree completely. What you're telling is true, don't get me wrong. It's the Error that I get from Java that troubles me.
    To resolve the classloading question, I changed my code as follows:
    package javax.swing;
    import java.lang.reflect.Proxy;
    import java.util.ArrayList;
    import java.util.Collection;
    import org.apache.commons.lang.ArrayUtils;
    public class NonPublicInterfaceProxyCreator {
        public static void main(String[] args) {
            // This works fine !
            doTest(WindowConstants.class);
            doTest2(WindowConstants.class);
            // This also ! The proxy class package is javax.swing as expected
            doTest(SomePackageInterfaceDefiningClass.SomeInnerPackageInterface.class);
            doTest2(SomePackageInterfaceDefiningClass.SomeInnerPackageInterface.class);
            // JDialog implements the package visible interface
            // javax.swing.TransferHandler.HasGetTransferHandler
            Collection<Class<?>> jdInterfaces = new ArrayList<Class<?>>();
            for (Class<?> interfaze : JDialog.class.getInterfaces()) {
                jdInterfaces.add(interfaze);
            Collection<Class<?>> strippedJdialogInterfaces = new ArrayList<Class<?>>(
                    jdInterfaces);
            for (Class<?> interfaze : jdInterfaces) {
                if (interfaze.getName().equalsIgnoreCase(
                        "javax.swing.TransferHandler$HasGetTransferHandler")) {
                    strippedJdialogInterfaces.remove(interfaze);
            // Without the package visible interface it works !
            doTest(strippedJdialogInterfaces.toArray(new Class<?>[0]));
            doTest2(strippedJdialogInterfaces.toArray(new Class<?>[0]));
            // With the package visible interface it fails
            doTest(jdInterfaces.toArray(new Class<?>[0]));
            doTest2(jdInterfaces.toArray(new Class<?>[0]));
        private static void doTest(Class... interfaces) {
            ClassLoader contextClassLoader = Thread.currentThread()
                    .getContextClassLoader();
            System.out.println("Classloader that creates proxy = " + contextClassLoader);
            try {
                Class clazz = Proxy.getProxyClass(contextClassLoader, interfaces);
                System.out.println("Class created = " + clazz
                        + " >>>> Implemented interfaces = "
                        + ArrayUtils.toString(clazz.getInterfaces()));
            } catch (Throwable e) {
                e.printStackTrace();
        private static void doTest2(Class... interfaces) {
            ClassLoader contextClassLoader = JDialog.class.getClassLoader();
            System.out.println("Classloader that creates proxy = " + contextClassLoader);
            try {
                Class clazz = Proxy.getProxyClass(contextClassLoader, interfaces);
                System.out.println("Class created = " + clazz
                        + " >>>> Implemented interfaces = "
                        + ArrayUtils.toString(clazz.getInterfaces()));
            } catch (Throwable e) {
                e.printStackTrace();
    }And here is the result when I run it on Java 1.6:
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    Class created = class $Proxy0 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Classloader that creates proxy = null
    Class created = class $Proxy1 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    Class created = class javax.swing.$Proxy2 >>>> Implemented interfaces = {interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface}
    Classloader that creates proxy = null
    java.lang.IllegalArgumentException: interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface is not visible from class loader
         at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353)
         at javax.swing.NonPublicInterfaceProxyCreator.doTest2(NonPublicInterfaceProxyCreator.java:64)
         at javax.swing.NonPublicInterfaceProxyCreator.main(NonPublicInterfaceProxyCreator.java:18)
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    Class created = class $Proxy3 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Classloader that creates proxy = null
    Class created = class $Proxy4 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    java.lang.IllegalAccessError: class javax.swing.$Proxy5 cannot access its superinterface javax.swing.TransferHandler$HasGetTransferHandler
         at java.lang.reflect.Proxy.defineClass0(Native Method)
         at java.lang.reflect.Proxy.getProxyClass(Proxy.java:504)
         at javax.swing.NonPublicInterfaceProxyCreator.doTest(NonPublicInterfaceProxyCreator.java:51)
         at javax.swing.NonPublicInterfaceProxyCreator.main(NonPublicInterfaceProxyCreator.java:41)
    Classloader that creates proxy = null
    Class created = class javax.swing.$Proxy6 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer,interface javax.swing.TransferHandler$HasGetTransferHandler}As you can see, I get an IllegalArgumantException telling me that my interface I try to proxy is not visible for JDialog's classloader, as I would expect. Remark that Java tells me that JDialog's classloader is null. Strange, isn't is?
    However I get an IllegalAccessError when I try to proxy TransferHandler$HasGetTransferHandler from my own classloader.
    Any reason why the error is different?

  • Public methods in a class

    hi
    i want to know whether there is any restriction in using infinite number of public methods in a java class.
    for example.
    i have class A.
    it does not extend or implement a class or an interface.
    so how many public methods i can write inside this classA.
    is there any restriction for the number of public methods???
    rgds

    kk_d wrote:
    i have class A.
    it does not extend or implement a class or an interface.Every class other than java.lang.Object directly or indirectly extends java.lang.Object.
    BIJ001 wrote:
    This compiles with 16000 methods:
    The same with 32000 methods however not: Because you probably ran into another limit (with those method invocations) -- the max. number of constant pool entries, 65534. And the number of available entries is even lower due to some required items, like this class name etc. (and the default constructor, which could probably left out, allowing for yet another 3 methods ;-)...
    // Make.java
    // Usage: java Make className
    import java.io.*;
    public class Make {
      public static void main(final String[] args) throws Throwable {
        final String srcFileName = args[0].concat(".java");
        if ((new File(srcFileName)).exists())
            throw new IllegalArgumentException();
        final FileWriter fw = new FileWriter(srcFileName);
        fw.write("public class " + args[0] + " {\n");
        int i;
        for (i = 1; i <= 65535 - 1 - 9; ++i)
            fw.write(
                    "  public static void meth" + i + "() {\n"
                    + "  }\n");
        fw.write("}\n");
        fw.close();
        System.out.println(
                srcFileName + ": #" + i + " methods\n"
                + "(compile with -g:none)" );
    }So 65526 is apparently the maximum number of methods that can be declared in a class in Java source file (and 65528 is probably the "real" upper limit wrt class file format).
    rgds

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

  • App rejected due to non-public api's

    Hi,
              My App rejected due to non-public api's.
    Apple's Comments: 
    2.5: Apps that use non-public
                                      "We found that your app uses one or more non-public APIs, which is not in compliance with the App Store Review Guidelines. The use of non-public APIs is not permissible because it can lead to a poor user experience should these APIs change.
    We found the following non-public API/s in your app:
    _updateView (I have the method name like "_updateView" in my source, can I change the name of the method. Is it works ? )
    If you have defined methods in your source code with the same names as the above-mentioned APIs, we suggest altering your method names so that they no longer collide with Apple's private APIs to avoid your application being flagged in future submissions.
    Additionally, one or more of the above-mentioned APIs may reside in a static library included with your application. If you do not have access to the library's source, you may be able to search the compiled binary using "strings" or "otool" command line tools. The "strings" tool can output a list of the methods that the library calls and "otool -ov" will output the Objective-C class structures and their defined methods. These techniques can help you narrow down where the problematic code resides."
                                    And in my application, I am using the FBConnect, SDWebImage library,  and Twitter+oAuth api's. These are non-public api's ? Now, can I integrate Jira (Crash Reporter) to my application? Can anybody solve my issue......
    Thanks & Regards,
    Rajesh Kumar Yandamuri

    I have the same problem what to do with below points from the apple.
    Requires help plz help me my app rejected two times with this points.
    We found that your app uses one or more non-public APIs, which is not in compliance with the App Store Review Guidelines. The use of non-public APIs is not permissible because it can lead to a poor user experience should these APIs change.
    We found the following non-public API/s in your app:
    _tearDown
    If you have defined methods in your source code with the same names as the above-mentioned APIs, we suggest altering your method names so that they no longer collide with Apple's private APIs to avoid your application being flagged in future submissions.
    Additionally, one or more of the above-mentioned APIs may reside in a static library included with your application. If you do not have access to the library's source, you may be able to search the compiled binary using "strings" or "otool" command line tools. The "strings" tool can output a list of the methods that the library calls and "otool -ov" will output the Objective-C class structures and their defined methods. These techniques can help you narrow down where the problematic code resides.
    We appreciate that you may have made the precautions in your code for using non-public APIs, however, there is no way to accurately or completely predict how an API may be modified and what effects those modifications may have. For this reason, we do not permit the use of non-public APIs in App Store apps.
    If there are no alternatives for providing the functionality your app requires, we encourage you to file an enhancement request. Or, try working with the Apple Developer Technical Support team to explore alternative solutions. 
    On occasion, there may be apps on the App Store that don't appear to be in compliance with the App Store Review Guidelines. We work hard to ensure that the apps on the App Store are in compliance and we try to identify any apps currently on the App Store that may not be. It takes time to identify these occurrences but another app being out of compliance is not a reason for your app to be.
    For discrete code-level questions, you may wish to consult with Apple Developer Technical Support. Please be sure to:
    - include the complete details of your rejection issues
    - prepare any symbolicated crash logs, screenshots, and steps to reproduce the issues for when the DTS engineer follows up.
    For information on how to symbolicate and read a crash log, please see Tech Note TN2151 Understanding and Analyzing iPhone OS Application Crash Reports.
    If you have difficulty reproducing this issue, please try testing the workflow as described in  <https://developer.apple.com/library/ios/qa/qa1764/>Testing Workflow with Xcode's Archive feature".

  • Can i call non -abstract method in abstract class into a derived class?

    Hi all,
    Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
    The following example will explain this Ques. in detail.
    abstract class A
    void amethod()
    System.out.println(" I am in Base Class");
    public class B extends A
    void amethod()
    System.out.println(" I am in Derived Class");
    public static void main (String args[])
    // How i code this part to call a method amathod() which will print "I am in Base Class
    }

    Ok, if you want to call a non-static method from a
    static method, then you have to provide an object. In
    this case it does not matter whether the method is in
    an abstract base class or whatever. You simply cannot
    (in any object oriented language, including C++ and
    JAVA) call a nonstatic method without providing an
    object, on which you will call the method.
    To my solution with reflection: It also only works,
    if you have an object. And: if you use
    getDeclaredMethod, then invoke should not call B's
    method, but A's. if you would use getMethod, then the
    Method object returned would reflect to B's method.
    The process of resolving overloaded methods is
    performed during the getMethod call, not during the
    invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
    class A {
        public void dummy() {
             System.out.println("Dymmy in A");
    class B extends A {
         public void dummy() {
              System.out.println("Dymmy in B");
         public static void main(String[] args) throws Exception {
              A tmp = new B();
              Class clazz = A.class;
              Method method = clazz.getDeclaredMethod("dummy", null);
              method.invoke(tmp, null);
    }Prints:
    Dymmy in B
    /Kaj

  • Non-abstract methods in a Abstract class

    Abstract Class can contain Non-abstract methods.
    and Abstract Classes are not instantiable as well
    So,
    What is the purpose of Non-abstract methods in a Abstract class.
    since we can't create objects and use it
    so these non-abstract methods are only available to subclasses.
    (if the subclass is not marked as abstract)
    is that the advantage that has.(availability in subclass)
    ??

    For example, the AbstractCollection class (in
    java.util) provides an implementation for many of the
    methods defined in the Collection interface.
    Subclasses only have to implement a few more methods
    to fulfill the Collection contract. Subclasses may
    also choose to override the AbstractCollection
    functionality if - for example - they know how to
    provide an optimized implementation based on
    characteristics of the actual subclass.Another example is the abstract class MouseAdapter that implements MouseListener, MouseWheelListener, MouseMotionListener, and that you can use instead of these interfaces when you want to react to one or two types of events only.
    Quoting the javadocs: "If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about."

  • Abstract method versus static and non-static methods

    For my own curiosity, what is an abstract method as opposed to static or non-static method?
    Thanks

    >
    Following this logic, is this why the "public static
    void main" 0r "Main" method always has to be used
    before can application can be run: because it belongs
    to the class (class file)?
    Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
    RObin

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Are there non-public classes in Java SDK?

    Or are ALL classes in all packages of the Java SDK public?
    I have looked in the sources spot checking and didn't find a non public (default) class.
    If all classes are public, why?
    There exists a means in Java language to define a class as default ("class MyClass" instead of "public class MyClass") visibility. So why isn't it used by Java SDK (if this is really true)?

    I dont know what language you're programming in.
    If you don't specify
    public class
    or
    private class
    the class is "protected".
    Read the spec.If you read the spec, you'll see that, with respect to a class:
    (per section 6.6.2) Classes from outside the package the class lives in that extend the class have access to protected members.
    (per section 6.6.5) Classes from outside the package this thing lives in that extend this class do not have access to default members.
    Relevant part of section 6.6.5 (Example: Default-Access Fields, Methods, and Constructors) is:
    If none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package.
    This is default access, not protected access
    Lee

  • Non static method cannot be referenced from a non static context

    Dear all
    I am getting the above error message in my program.
    public void testing(Vector XY){
    RecStore.checkUnits(XY);
    }method checkUnits is non static and cannont be called from a non static context. I don't see the word static anywhere...
    I have done a wider search throughout the main class and I'm haven't got any static their either.
    Any ideas?
    Thanks
    Dan

    Yup
    I had pared down my code, infact it is being called from within a large if statement.Irrelevant.
    But the same thing still holds that there is no static keyword used.Read my previous post. Calling checkUnits using the class name:
    RecStore.checkUnits(XY);implies a static context--in order for that call to work, checkUnits must be static. That's what your error message is saying--you are trying to call the non-static method "checkUnits" from the static context of using the class name "RecStore."

Maybe you are looking for

  • Apple ID on multiple iPads

    At my education institution we own a number of iPads, around sixty. At present they have all been supervised by Apple Configurator and enrolled in Merkai. I have 15 of them set up with only one profile from Apple Configurator, which is for the wifi.

  • HTTP to RFC scenario---- need help

    HI, I am trying to send the pay load through the Runtime workbench - > Adapter Engine -> Test Message, on pressing the send message it says that message is send but I cannot see the message in XI. I have done the following steps:- 1) Check the string

  • Menu doesn't include "Music"

    Can't account for this change, but all of a sudden, the menu on my iPod starts with "Photos." It will play if I go to "shuffle," but I can't get to the "music" menu. It's fully charged, has been reset, has most recent software update... Any ideas?

  • IPod not working in iTunes 8.2.1.6 and TS1363

    A question about Knowledge Base entry TS1363: I have been tring to get my iPod Shuffle 2nd Gen to work with 8.2.1.6. I notice that Apple has added more suggestions for fixing the problem I have. I am use Windows XP Home with SP3. When I connect the i

  • ITunes in mono is a needed function

    Unless I've overlooked something, I can't find any way to output my iTunes tunes in monophonic, or to change the system settings in OS X to do so. There are several reasons to want mono output: A blown speaker... People who are deaf in one ear who wa