Creation of a static class with private methods

I'm new to java programming and am working on a project where I need to have a static class that does a postage calculation that must contain 2 private methods, one for first class and one for priority mail. I can't seem to figure out how to get the weight into the class to do the calculations or how to call the two private methods so that when one of my other classes calls on this class, it retrieves the correct postage. I've got all my other classes working correct and retrieving the information required. I need to use the weight from another class and return a "double". Help!!!
Here's my code:
* <p>Title: Order Control </p>
* <p>Description: Order Control Calculator using methods and classes</p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: Info 250, sec 001, T/TH 0930</p>
* @author Peggy Blake
* @version 1.0, 10/29/02
import javax.swing.*;
public class ShippingCalculator
static double firstClass, priorityMail;
//how do I get my weight from another class into this method to use??? not sure I understand how it works.
public static double ShippingCalculator(double weight)
String responseFirstClass;
double quantity, shippingCost;
double totalFirstClass, firstClass, priorityMail, totalShipping;
double priorityMail1 = 3.50d;//prioritymail fee up to 1 pound
double priorityMail2 = 3.95d;//prioritymail fee up to 2 pounds
double priorityMail3 = 5.20d;//prioritymail fee up to 3 pounds
double priorityMail4 = 6.45d;//prioritymail fee up to 4 pounds
double priorityMail5 = 7.70d;//prioritymail fee up to 5 pounds
quantity = 0d;//ititialization of quantity
// weight = 0d;//initialization of weight
// shippingCost = 0d;
//calculation of the number of items ordered..each item weights .75 ounces
quantity = (weight/.75);
if (quantity <= 30d)
//add 1 ounce to quantities that weigh less than 30 ounces
weight = (weight + 1);
else
//add 2 ounces to quantities that weigh more than 30 ounces
weight = (weight + 2);
if (weight > 80d)
//message to orderclerk ..order over 5 lbs, cannot process
JOptionPane.showMessageDialog(null, "Order exceeded 5 lbs, cannot process");
//exit system, do not process anything else
System.exit (0);
else
if (weight < 14d)
//send message to customer: ship firstclass or priority, y or n
responseFirstClass = JOptionPane.showInputDialog(null, "Ship first class? y or n?");
if (responseFirstClass.equals("y"))
//compute FirstClass shipping cost
totalFirstClass = ((weight - 1) * .23d) + .34d;
firstClass = totalFirstClass;
else
//compute PriorityMail cost for orders less than 14 ounces
priorityMail = (priorityMail1);
else
if (weight <=16d)
//compute totalshipping for orders up to 16 ounces
priorityMail = (priorityMail1);
else
if (weight <=32d)
//compute totalshipping for orders up to 32 ounces
priorityMail = (priorityMail2);
else
if (weight <=48d)
//compute totalshipping for orders up to 48 ounces
priorityMail = (priorityMail3);
else
if (weight <= 64d)
//compute totalshipping for orders up to 64 ounces
priorityMail = (priorityMail4);
else
//compute totalshipping for orders up to 80 ounces
priorityMail = (priorityMail5);
priorityMail = 0d;
firstClass = 0d;
firstClassMail ();
priorityMailCost ();
//I think this is where I should be pulling the two methods below into my code, but can't figure out how to do it.
shippingCost = priorityMail + firstClass;
return (shippingCost);
}//end method calculate shipping
private static double firstClassMail()//method to get first class ship cost
return (firstClass);
}//end method firstclass shipping
private static double priorityMailCost()//method to get priority mail cost
return (priorityMail);
}//end method priorityMail
}//end class shipping calculator

public class A {
public String getXXX () {
public class B {
A a = new A();
public void init () {
a.getXXX();
}

Similar Messages

  • Extending classes with private methods?

    my understanding of extending classes is that you gain all the functions and methods of that class thus You could over ride any one of them. How ever I am confused on weather or not you inherit and can over ride private methods of the class you are extending or if you have to have all methods public in an extended class.
    hope that makes sense, an example can bee seen bellow.
    package
         public class Class1
              public function apples():void
                   //some code
              private fnctuin bananas():void
                   //more code
    package
         public class Class2 extends Class 1
              override public function apples():void
                   //i changed code
              //can I over ride bananas?

    you can only override methods that would be inherited.  a private method won't be inherited:
    http://www.kirupa.com/forum/showthread.php?223798-ActionScript-3-Tip-of-the-Day/page5

  • Why can't classes with private constructors be subclassed?

    Why can't classes with private constructors be subclassed?
    I know specifying a private nullary constructor means you dont want the class to be instantiated or the class is a factory or a singleton pattern. I know the workaround is to just wrap all the methods of the intended superclass, but that just seems less wizardly.
    Example:
    I really, really want to be able to subclass java.util.Arrays, like so:
    package com.tassajara.util;
    import java.util.LinkedList;
    import java.util.List;
    public class Arrays extends java.util.Arrays {
        public static List asList(boolean[] array) {
            List result = new LinkedList();
            for (int i = 0; i < array.length; i++)
                result.add(new Boolean(array));
    return result;
    public static List asList( char[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Character(array[i]));
    return result;
    public static List asList( byte[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Byte(array[i]));
    return result;
    public static List asList( short[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Short(array[i]));
    return result;
    public static List asList( int[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Integer(array[i]));
    return result;
    public static List asList( long[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Long(array[i]));
    return result;
    public static List asList( float[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Float(array[i]));
    return result;
    public static List asList( double[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Double(array[i]));
    return result;
    // Now that we extend java.util.Arrays this method is not needed.
    // /**JCF already does this so just wrap their implementation
    // public static List asList(Object[] array) {
    // return java.util.Arrays.asList(array);
    public static List asList(Object object) {
    List result;
    Class type = object.getClass().getComponentType();
    if (type != null && type.isPrimitive()) {
    if (type == Boolean.TYPE)
    result = asList((boolean[])object);
    else if (type == Character.TYPE)
    result = asList(( char[])object);
    else if (type == Byte.TYPE)
    result = asList(( byte[])object);
    else if (type == Short.TYPE)
    result = asList(( short[])object);
    else if (type == Integer.TYPE)
    result = asList(( int[])object);
    else if (type == Long.TYPE)
    result = asList(( long[])object);
    else if (type == Float.TYPE)
    result = asList(( float[])object);
    else if (type == Double.TYPE)
    result = asList(( double[])object);
    } else {
    result = java.util.Arrays.asList((Object[])object);
    return result;
    I do not intend to instantiate com.tassajara.util.Arrays as all my methods are static just like java.util.Arrays. You can see where I started to wrap asList(Object[] o). I could continue and wrap all of java.util.Arrays methods, but thats annoying and much less elegant.

    Why can't classes with private constructors be
    subclassed?Because the subclass can't access the superclass constructor.
    I really, really want to be able to subclass
    java.util.Arrays, like so:Why? It only contains static methods, so why don't you just create a separate class?
    I do not intend to instantiate
    com.tassajara.util.Arrays as all my methods are static
    just like java.util.Arrays. You can see where I
    started to wrap asList(Object[] o). I could continue
    and wrap all of java.util.Arrays methods, but thats
    annoying and much less elegant.There's no need to duplicate all the methods - just call them when you want to use them.
    It really does sound like you're barking up the wrong tree here. I can see no good reason to want to subclass java.util.Arrays. Could you could explain why you want to do that? - perhaps you are misunderstanding static methods.
    Precisely as you said, if they didn't want me to
    subclass it they would have declared it final.Classes with no non-private constructors are implicitly final.
    But they didn't. There has to be a way for an API
    developer to indicate that a class is merely not to be
    instantiated, and not both uninstantiable and
    unextendable.There is - declare it abstract. Since that isn't what was done here, I would assume the writers don't want you to be able to subclass java.util.Arrays

  • Enhanced SAP class with new methods - Not showing these from standard task

    Dear Gurus,
    I have enhanced SAP standard class with new methods. After I have activated my new methods and would like to create a workflow task using these new methods. when I create a task and input object category as "ABAP Class" and object type is SAP enhanced class. When I try to drop down for methods SAP is not showing my new methods. I do not know why. Am I missing any? Any help would be appreciated.
    Note: Remember I am trying to use SAP ABAP class custom methods.
    Thanks,
    GSM

    Hi,
    Your thread has had no response since it's creation over
    2 weeks ago, therefore, I recommend that you either:
    - Rephrase the question.
    - Provide additional Information to prompt a response.
    - Close the thread if the answer is already known.
    Thank you for your compliance in this regard.
    Kind regards,
    Siobhan

  • In which case we need a class with all methods defined as abstract ?

    In which case we need : A class with all methods defined as abstract (or should we go for Interface always in this case)

    The concept of interface and abstract class overlaps sometime, but we can have the following thumb rule to use them for our specific need:
    1) Interface: This should be use for code structuring. They standardize your application by providing a specific contract within and outside. If you think abstract class also provide structure, then reconsider as it limits the structure re-usability when there are many super-classes to inherit from. Java allow multiple inheritance by interface and not by Abstract class.
    2) Abstract Class: This should be use for code-reusability. Interface doesn't have any code so can't be used for code-reusability.
    Actually we can use both to provide the best.Taking a refernce to J2EE framework, the "Servlet" is an interface. It laids down the contract/structure for any code to be a servlet.
    But the "GenericServlet" class is an abstract class which provides implementation of some of the methods defined in the "Servlet" interface and leave some method abstract.
    Thus we see that the "Servlet" interface standardise the structure and the "GenericServlet" abstract class gives code re-usability.
    Original Question:
    In which case we need a class with all methods defined as abstract ?To this question, as all methods are abstarct we don't have option for code-reusability. so why not add standard structure concept to your application. So if there is not any restriction on making the field variable(if any) as final, we should go with the interface concept.

  • Testing ActionScript classes with native methods?

    Hi,
    I have an ActionScript class that I'm writing and would like to test using FlexUnit.
    The only issue is that the ActionScript class has a member in it that is a class with native methods.
    So, I get the following error when trying to run a test of that ActionScript class:
    VerifyError: Error #1079: Native methods are not allowed in loaded code.
    Does anyone know of a way to get around this?  FlexUnit seems not to like native methods being present.
    Thanks,
    Matt

    Hi casdvm,
    by definition, you only own objects that you created using one of the alloc* methods, copy: or new:. All other objects (IIRC with a few noted exceptions) are autoreleased.
    If you create convenience methods in your own class, you should follow the same rule. For example, if you have a class Pet and want to implement the method +petWithName, your code might look something like that:
    + petWithName: (NSString *)name
    return [[[Pet alloc] initWithName: name] autorelease];
    Alex

  • Private inner class with private constructor

    I read that if constructor is public then you need a static method to create the object of that class.
    But in the following scenario why I am able to get the object of PrivateStuff whereas it has private constructor.
    I am messing with this concept.
    public class Test {
          public static void main(String[] args) {          
               Test t = new Test();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }

    A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
    * Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]
    Your main method is within the body of the top level class, so the type (the inner class) and method are accessible.
    eg:
    class ImInTheSameSourceFileAsInnerAccessTest {
        public static void main(String[] args) {          
            InnerAccessTest t = new InnerAccessTest();
            InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    public class InnerAccessTest {
          public static void main(String[] args) {          
               InnerAccessTest t = new InnerAccessTest();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }Result:
    $ javac -d bin src/InnerAccessTest.java
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    2 errors
    Edited by: pm_kirkham on 20-Jan-2009 10:54 added example of 'in the same source file'

  • Abstract Method in a Class with implemented method

    I have a class which already has methods Implemented.I mean thse metgods are not abstract.I want only one method to be abstarct which will be overrideen by its subclass or derived Class
    I have never tried this
    Does anyone knows how to do this
    If yes could you give me syntax of the method
    Thanks in advance
    CSJakharia

    javax.swing.JComponent is an example of an abstract
    class with no abstract methods. That is why the
    following works:
    JComponent component = new JComponent(){};
    Not to forget you cannot instantiate abstarct classes
    public abstract class Test
    public String getName()
    return "Mike";
    public static void main(String[] args)
    Test tt = new Test();
    System.out.println(tt.getName());
    }and you would get the error
    The type Test cannot be instantiated.
    You remove the abstract keyword and it would compile
    good.No I am not misinterpreting I know what he is saying but I am closing the door of misinterpretation which I felt was possible. ;)
    cheers

  • Class with private constructor can be extended or not

    Hi All,
    I have a doubt.
    if a class has private constructor and there are some methods in this class.Can this class be extended and if yes how can we call its method in subclass?
    Thanks
    Sumit

    Karanjit wrote:
    If a class contains only private constructors, then it cannot be extended.Err... not the whole story!
    public class Sabre20090603a
        static class Fred extends Sabre20090603a
            Fred()
                super();
        private Sabre20090603a()
    }

  • Help with Declaring a Class with a Method and Instantiating an Object

    hello all i am having trouble understanding and completing a lab tutorial again!
    im supposed to compile an run this code then save work to understand how to declare aclass with a method an instantiate an object of the class with the following code
    // Program 1: GradeBook.java
    // Class declaration with one method.
    public class GradeBook
    // display a welcome message to the GradeBook user
    public void displayMessage()
    System.out.println( "Welcome to the Grade Book!" );
    } // end method displayMessage
    } // end class GradeBook
    // Program 2: GradeBookTest4.java
    // Create a GradeBook object and call its displayMessage method.
    public class GradeBookTest
    // main method begins program execution
    public static void main( String args[] )
    // create a GradeBook object and assign it to myGradeBook
    GradeBook myGradeBook = new GradeBook();
    // call myGradeBook's displayMessage method
    myGradeBook.displayMessage();
    } // end main
    } // end class GradeBookTest4
    i saved above code as shown to working directory filename GradeBookTest4.java
    C:\Program Files\Java\jdk1.6.0_11\bin but recieved error message
    C:\Program Files\Java\jdk1.6.0_11\bin>javac GradeBook4a.java GradeBookTest4.java
    GradeBookTest4.java:2: class, interface, or enum expected
    ^
    GradeBookTest4.java:27: reached end of file while parsing
    ^
    2 errors
    can someone tell me where the errors are because for class or interface expected message i found a solution which says 'class? or 'interface' expected is because there is a missing { somewhere much earlier in the code. i dont know what "java:51: reached end of file while parsing " means or what to do to fix ,any ideas a re appreciated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Doesn't solve your problem, but this works for me...
    public class GradeBook
      public void displayMessage() {
        System.out.println( "Welcome to the Grade Book!" );
      public static void main( String args[] ) {
        try {
          GradeBook gradeBook = new GradeBook();
          gradeBook.displayMessage();
        } catch (Exception e) {
          e.printStackTrace();
    }

  • Exception when creating instance of a class with native method by JNI

    I am trying to use JNI - I want to have a Java class Foo have a
    method, that is a native C function.
    I follow the Sun's tutorial
    http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnie...
    exactly, and everything compiles fine, and I have compiled my C .dll
    as well (on Win XP). So I am ready to run - ...
    Now when I finally try to run the Java application, it throws this
    exception when it tries to create the Foo instance:
    at Foo.<init>(Foo.java:11)
    at
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
    orAccessorImpl.java:39)
    at
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
    onstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:
    513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:786)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:715)
    at sun.applet.AppletPanel.run(AppletPanel.java:369)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: java.security.AccessControlException: access denied
    (java.lang.Runtim
    ePermission loadLibrary.Foo)
    Why would this be so??? Thank you for your insights

    Mark_Galeck wrote:
    I am trying to use JNI - I want to have a Java class Foo have a
    method, that is a native C function.
    I follow the Sun's tutorial
    http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jnie...
    exactlyNot quite exactly. Yours is an applet, theirs is an application.
    Applets are not allowed many things that applications can do.
    Among them, loading native libraries.

  • How to clear a private static class attribute once it's been created?

    <pre>I'm working with an instance of a complex Class object that has been created using the function module <br>HRXSS_CAT_APPLICATION_INIT. The Class object that I am trying to work with is<br> CL_XSS_CAT_BUSINESS_LAYER and in particular its Static Private component attribute PROFILE.<br>
    The issue that I am having is that the first call of this function module creates and populates the Static Private component attribute, <br>PROFILE, for the instance of this Class and I do not know how to initialize it once it's been created. The PROFILE attribute is an <br>object reference to an instance of Class CL_XSS_CAT_PROFILE. <br>
    I want to reset/intialize this Static Private component. I can then call a Class Method with<br> different parameters so that it repopulates PROFILE with different attributes. <br>There is no Public method to do this in CL_XSS_CAT_BUSINESS_LAYER and even the Private method<br> INIT_PROFILE, the logic first checks to see if the PROFILE component is initial before creating a new PROFILE<br> object instance. All the Attributes of the CL_XSS_CAT_PROFILE object are Static and Private.
    <br>
    I would appreciate any insight anyone might have in how to reset/initialize this Class component attribute.<br><br>
    Thanks much,<br>
    <br>
    Graham<br>
    Sample code snippet is as follows:
    <br><br>
    DATA: lr_cats_application_rfc TYPE REF TO IF_XSS_CAT_APPLICATION_RFC,
    lr_core TYPE REF TO IF_XSS_PT_APPLICATION_CORE,
    lr_core TYPE REF TO CL_XSS_CAT_1_APPLICATION_CORE,
    lr_instance TYPE REF TO CL_XSS_CAT_APPLICATION,
    lr_business_layer TYPE REF TO CL_XSS_CAT_BUSINESS_LAYER,
    lr_profile TYPE REF TO CL_XSS_CAT_PROFILE,
    lr_profile_temp TYPE REF TO cl_xss_cat_profile.
    DATA: l_employee TYPE pernr_d.
    DATA: l_employee_tab TYPE rhxss_cat_employee_t.
    CASE im_command.
    WHEN 'DATESELECTION_PRVPERIOD'.
    *-> navigate to object component reference for CL_XSS_CAT_PROFILE instance
    lr_cats_application_rfc = im_ref_to_parameter_cache->REF_TO_APPLICATION.
    *-> navigate to object component reference for CL_XSS_CAT_1_APPLICATION_CORE
    lr_core ?= lr_cats_application_rfc->get_core( ).
    *-> navigate to object component reference for CL_XSS_CAT_BUSINESS_LAYER
    lr_business_layer = lr_core->business_layer.
    *-> navigate to object component reference for CL_XSS_CAT_PROFILE
    lr_profile = lr_business_layer->get_profile( ).
    l_employee = im_ref_to_parameter_cache->pernr.
    append l_employee to l_employee_tab.
    <br><br>
    *THIS IS WHERE I AM HAVING ISSUES...I WOULD LIKE TO CLEAR/INITIALIZE THE STATIC PRIVATE COMPONENT<br> LR_BUSINESS_LAYER->PROFILE BEFORE CALLING THE METHOD INITIALIZE_FOR_TIME_RECORDING<br>
    <br>
    <br><br>*THE FOLLOWING LINE FAILS ON A SYNTAX CHECK WITH 'FIELD "PROFILE" IS UNKNOWN. IT IS NEITHER IN <br>ONE OF THE *SPECIFIED TABLES NOR DEFINED BY A "DATA" STATEMENT
    <br>
    clear: lr_business_layer->profile.
    CALL METHOD lr_business_layer->initialize_for_time_recording
    EXPORTING
    im_employee_tab = l_employee_tab
    im_profile_id = 'MODAPPR1'
    im_startdate = sy-datum
    EXCEPTIONS
    pernr_not_enqueued = 1
    no_pernr_for_user_found = 2
    profile_not_found = 3.</pre>
    Edited by: Matt on Aug 1, 2009 12:44 PM

    OK...I apologize but I did not dig deep enough to see that the Enhancement Framework allows for the addition of Methods to Classes/Interfaces. Most of this ABAP OO stuff is still quite new to me so I'm struggling with syntax and what is and isn't possible based on how everything is declared. I guess now that I know I can do this I am having some problems understanding how singleton Class objects work and how to 'reset' them.
    The Class instance based on CL_XSS_CAT_BUSINESS_LAYER has a Static Private attribute PROFILE that is an object reference to the singleton Class instance CL_XSS_CAT_PROFILE.
    The singleton Class instance of CL_XSS_CAT_PROFILE has all of its attributes set to Static Private. If you look at this Class in SE80 you see that one of its attributes is also called PROFILE and is an object reference variable to itself.
    So the issue I am having is how to go about 'initializing' this singleton object so that I can 'recreate' this singleton object using a copy of the existing S
    I used the enhancement framework to create a copy of the CL_XSS_CAT_BUSINESS_PROFILE Instance Private Method INIT_PROFILE , called in INIT_PROFILE2, but I am not sure how to 'clear/reset' the instance of the CL_XSS_CAT_PROFILE object.
    Since PROFILE is an attribute of the CL_XSS_BUSINESS_LAYER object, I thought that a simple CLEAR PROFILE would reset the object but this is not the case. Within this method the FREE clears the value of the reference variable PROFILE but as soon as you step into the method me->init_profile, the value of PROFILE goes back to what it was. I need for all of the CL_XSS_CAT_PROFILE instance attributes to be reset or initialized so I can fill them again. I think I'm getting confused on the scope of things...should I be enhancing the CL_XSS_CAT_PROFILE Class with 'setter' methods so I can initialize all of the Static Private attributes that way instead of trying to clear all the attributes at a higher call level?
    Any assistance with helping me with my thought process or approach to this would be much appreciated.
    METHOD INIT_PROFILE2.
    FREE PROFILE.  >>> is reset but it does not carry through to next method call and does not clear all the attributes of the object referenced in PROFILE
    CALL METHOD me->init_profile
    EXPORTING
    IM_PROFILE_ID = im_profile_id
    etc...

  • Unusual use of interface defining static factory class with getInstance

    This question is prompted by a recent New to Java forum question ask about the differences between Interfaces and Abstract classes. Of course one of the standard things mentioned is that interfaces cannot actually implement a method.
    One of my past clients, one of the 500 group, uses interfaces as class factories. The interface defines a pubic static class with a public static method, getInstance, that is called to generate instances of a class that implements the interface.
    This architecture was very object-oriented, made good use of polymorphism and worked very well. But I haven't seen this architecture used anywhere else and it seemed a little convoluted.
    Here is a 'pseudo' version of the basic interface template and use
    -- interface that defines public static factory class and getInstance method
    public interface abc {
        public static class FactoryClass
            public static abc getInstance ()
                return (abc) FactoryGenerator(new abcImpl(), abc.class);
    -- call of interface factory to create an instance
    abc myABC = abc.Factory.getInstance();1. Each main functional area ('abc' in the above) has its own interface factory
    2. Each main functional area has its own implementation class for that interface
    3. There is one generator (FactoryGenerator) that uses the interface class ('abc.class') to determine which implementation class to instantiate and return. The generator class can be configured at startup to control the actual class to return for any given interface.
    I should mention that the people that designed this entire architecture were not novices. They wrote some very sophisticated multi-threaded code that rarely had problems, was high performance and was easy to extend to add new functionality (interfaces and implementing classes) - pretty much plug-n-play with few, if any, side-effects that affected existing modules.
    Is this a best-practices method of designing factory classes and methods? Please provide any comments about the use of an architecture like this.

    Thanks for the feedback.
    >
    I don't see how 'the generator class can be configured at startup to control the actual class to return for any given interface' can possibly be true given this pseudo-code.
    >
    I can see why that isn't clear just from what is posted.
    The way it was explained to me at the time is that the interface uses standard naming conventions and acts like a template to make it easy to clone for new modules: just change 'abc' to 'def' in three places and write a new 'defImpl' class that extends the interface and the new interface and class can just 'plug in' to the framework.
    The new 'defImpl' class established the baseline functionality that must be supported. This line
    return (abc) FactoryGenerator(new abcImpl(), abc.class);uses the initial version of the new class that was defined, 'abcImpl()', when calling the FactoryGenerator and it acted as a 'minimum version supported'. The generator class could use configuration information, if provided, to provide a newer class version that would extend this default class. Their reasoning was that this allowed the framework to use multiple versions of the class as needed when bugs got fixed or new functionality was introduced.
    So the initial objects would be an interface 'abc' and a class 'abcImpl'. Then the next version (bug fixes or enhancements) would be introduced by creating a new class, perhaps 'abcImpl_version2'. A configuration parameter could be passed giving 'abcImpl' as the base class to expect in the FactoryGenerator call and the generator would actually create an instance of 'abcImpl_version2' or any other class that extended 'abcImpl'.
    It certainly go the job done. You could use multiple versions of the class for different environments as you worked new functionality from DEV, TEST, QA and PRODUCTION environments without changing the basic framework.
    I've never seen any Java 'pattern' that looks like that or any pattern where an interface contained a class. It seemed really convoluted to me and seems like the 'versioning' aspect of it could have been accomplished in a more straightforward manner.
    Thanks for the feedback. If you wouldn't mind expanding a bit on one comment you made then I will mark this ANSWERED and put it to rest.
    >
    I don't mind interfaces containing classes per se when necessary
    >
    I have never seen this except at this one site. Would you relate any info about where you have seen or used this or when it might be necessary?

  • Class Private Methods

    I'm doing a number of instrument drivers in LabVIEW 8.20 and am using the OO features which so far I'm really liking.
    At present I have my class with various methods in it that are called from a TestStand sequence, but there are some methods that are only called from within the class i.e. private methods - is there any way of defining a method as being private to other methods in the class?
    I noticed that on one of the instrument driver examples in the help that one of the class sub-folders had a little red key on it that looked as though it was indicating that files within this folder were private - is this what I'm looking for and how would I do that?
    Many thanks in advance for any responses,
    David Clark
    CLA | CTA
    CLA Design Ltd
    Hampshire, England

    I've found out how to do it :-
    (from help file)
    Setting the Access Scope of Member VIs
    You can set the access scope of a member VI to control user access to the member VI. Complete the following steps to set the access scope of a member VI.
    In the Project Explorer window, right-click the LabVIEW class icon for the class whose member VI access you want to change. The Class Properties dialog box appears.
    Select Item Settings from the Category list.
    To customize the access scope of items in the LabVIEW class, select an item from the Contents list on the Item Settings page.
    In the Access Scope section, select from the following options:
    Public—Any VI can call the member VI as a subVI.
    Protected—Only VIs within the same class or a descendant class can call the member VI. Protected member VIs display a dark yellow key glyph in the Project Explorer window.
    Private—Only VIs within the same class can call the member VI. Private member VIs display a red key glyph in the Project Explorer window.
    Repeat steps 3 and 4 for all items for which you want to change the access scope.
    Click the OK button to close the Class Properties dialog box.
    David Clark
    CLA | CTA
    CLA Design Ltd
    Hampshire, England

  • Typesafe enums with private access - strange or useful?

    Given the class listed at the bottom, you'll notice that it's possible to specify a typesafe enum, and restrict that enum to clients in such a way that - and here's the strange part - the constant class is not exported in the api, despite the fact that it's required as an argument to the constructor.
    In other words you can legally state:
    MyClass myClass = new MyClass(MyClass.PLAIN);but not:
    MyClass.Constant constant = MyClass.PLAIN;
    MyClass myClass = new MyClass(constant);Anyone else noticed this? (Still coming to terms with the meaning of it).
    /k1
    Example code:
    * Type safety demo
    package blah;
    * Demo class showing the use of inaccessible constants
    public class MyClass {
         /** My first constant */
         public static final Constant FIRST;
         /** My second constant */
         public static final Constant SECOND;
         /* The instance constant field */
         private Constant constant;
         /* static initialiser for the constants */
         static {
              FIRST = new Constant("First");
              FANCY = new Constant("Second");
          * @param constant The constant spec
         public MyClass(Constant constant) {
              super();
              this.constant = constant;
         private static class Constant {
              private String name;
               * @param name The name of my constant
              public Constant(String name) {
                   this.name = name;
    }

    And indeed outside the package...
    package blah.test;
    import blah.*;
    public class Driver {
          * Main method for the sake of demonstration...
         public static void main(String[] args) {
              Object[] constants = MyClass.VALUES;
              for (int i = 0; i < constants.length; i++) {
                   System.out.println(constants);
                   MyClass myClass = new MyClass(constants[i]);
                   System.out.println(myClass);
    ...then...
    * Type safety demo
    package blah;
    * Demo class showing the use of inaccessible constants
    public class MyClass {
         /** My first constant */
         public static final Constant FIRST = new Constant("First");
         /** My second constant */
         public static final Constant SECOND = new Constant("Second");
         /** An array of the constants */
         public static final Constant[] VALUES = { FIRST, SECOND };
         /* The instance constant field */
         private Constant constant;
          * @param constant The constant spec
         public MyClass(Object constant) {
              super();
              if (constant instanceof Constant) {
                   this.constant = (Constant)constant;
         private static class Constant {
              private String name;
               * @param name The name of my constant
              public Constant(String name) {
                   this.name = name;
               * @return The name of the constant
              public String toString() {
                   return name;

Maybe you are looking for