"Good programming practice" question about writing classes

I am taking a java class this year and my teacher has taught us to never use global variables in a class (but still private). I find it much easier to explain with a simple example. Say I have a class that looks like this:
public class Demo
        private int int1, int2;
     public Demo()
          int1 = 1;
          int2 = 2;
     public void demoMethodOne(int int1, int int2)
          //... code using the ints passed to the method
     public void demoMethodTwo()
          //... code directly accessing the private ints of the class
        public int getInt1() { return int1; }
        public int getInt2() { return int2; }
}My teacher says to ALWAYS use methods of the type demoMethodOne (to pass all of the variables it will use to it) and avoid using the type demoMethodTwo. But in my programming experience, I have found it very repetitive and pointless to use that method in some cases. For example if I call demoMethodOne like this:
demoMethodOne(demo.getInt1(), demo.getInt2());
That seems very repetitive but that is how I am told to do it. Should I program that way even if it seems very pointless or is it ok to use "public" variables like in demoMethodTwo. Thanks.

I think you may have misunderstood your teacher.
If your object method is doing something with the object's state, then it's perfectly appropriate to modify the object's fields, which embody the state.
And generally it's good to adopt a functional programming approach, in which there are few side effects. This principle is sort of independent of the previous one.
The danger is when you treat object fields as global variables (and not as the embodiment of the object's state). In this case the global variable doesn't really represent anything, it's just a place to store data temporarily to avoid designing your methods properly. So for example you'd have two methods, one sets a field and then calls another method, which reads the field; the field doesn't really mean anything to the object as a whole, it's just a lazy way to pass data between the two methods. This is asking for bugs. The correct thing would have been to pass the value as an argument to the second method.
Also, if you have a method that doesn't really express the behavior or effect the state of an object, but is called just for its return value (like some kind of utility method), then it's pointless and dangerous to make it effect the state of an object.

Similar Messages

  • Good programming practice - Abstract class

    Hi all,
    I have been trying to help another soul in this forum, and came to the conclusion that I don't know good
    programming practice when it comes to abstract classes.
    Is this correct?
    You CAN implement methods in an abstract class, but it's not recommended.
    I have NEVER done this...when is there possibly a need to?
    Regards.
    / k

    Yes, absolutely, you can implement methods in an abstract class. Any method that all subclasses will perform in the same way can be implemented in the abstract base class. If subclasses perform similiar functions depending on their type you declare those as abstract in the base class. Here is a contrived example that I have seen on job interviews.
    Suppose your developing an application that draws on a panel. We want to provide some canned shapes such as a circle, a square and a triangle. We want to be able to draw the shape set or get its color and calculate its area.
    Let's define an abstract base class Shape
    public abstract class Shape{
        private Color myColor;
       //  since color has nothing to do with what kind of shape we're working with, create concrete implementation
       public Color getColor(){
            return myColor;
    public void setColor(Color newColor){
       myColor = newColor;
    // however, drawing the shape and calculation its area are depending on the actual shape.
    public abstract void draw();
    public abstract double getArea();
    // so then Square would be something like
    public class Square extends Shape{
       public double get Area()
          return sideLength * sideLength  // assumes somehow we know sideLength
    public void draw(){
                  // concrete implementation
    }we can do the same things for Circle class and Triangle class.
    And, if you think about it you'll notice that we could have made a Rectangle class and then Square would be a subclass of Rectangle where both dimensions are equal.
    I hope that somewhat strained example helps answer your question.
    DB

  • Good programming practices:   creating Iterator objects

    Hi,
    This is a question about Good programming practices for creating Iterator objects of ArrayList objects. The following line of code works fine in my program (as ridiculous as it may sound):
            Iterator cheesesIterator = cheeses.iterator();but I was wondering whether Java is automatically inserting the <Type> and new code to make:
            Iterator<String> cheesesIterator = new cheeses.iterator();and therefore whether it is good practice to use these everytime? Thank you. ("full" code shown below:)
    import java.util.ArrayList;
    import java.util.Iterator;
    public class DemonstrateIterator
        private ArrayList<String>  cheeses;
         * constructor:
        public DemonstrateIterator()
            cheeses = new ArrayList<String>();
            cheeses.add("Emmentaler");
            cheeses.add("Cheddar");
            cheeses.add("Stilton");
            cheeses.add("Brie");
            cheeses.add("Roquefort");
        public void listCheeses()
             //make an iterator object of the ArrayList object
            Iterator cheesesIterator = cheeses.iterator();
            while (cheesesIterator.hasNext()) {
                System.out.println(cheesesIterator.next());
            /** Exploring the toString and Super functions. **/       
            System.out.println("\na toString call to Super returns: " +
                                              super.toString() + "\n");
    }

    AJ-Phil wrote:
    Hi,
    This is a question about Good programming practices for creating Iterator objects of ArrayList objects. The following line of code works fine in my program (as ridiculous as it may sound):
            Iterator cheesesIterator = cheeses.iterator();but I was wondering whether Java is automatically inserting the <Type> and new code to make:
            Iterator<String> cheesesIterator = new cheeses.iterator();and therefore whether it is good practice to use these everytime? TFirst, new chesses.iterator() won't compile.
    iterator() is just a method that returns an iterator. It constructs an instance of a private or nested class that implements iterator, and returns a reference to it.
    As for the <T>, when you declare List<String>, that parameterizes that list with type String. The iterator() method returns Iterator<T>. You can look at the source code for yourself. It's in src.zip that came with your JDK download.
    Separate from that is your declaration of that variable as type Iterator, rather than Iterator<String>. Regardless of what you declare on the LHS, the iterator() method returns Iterator<T>. Your bare Iterator is essentially Iterator<Object> or Iterator<? extends Object> (not sure which, or what the difference is), which is assignment compatible with Iterator<T>. If you had declared it Iterator<String>, you wouldn't have to cast after calling next().
    Edited by: jverd on Nov 23, 2008 11:33 AM

  • Do IOS app developers follow any good program practices?

    I've had my iPad (original) a little over two years now, and I can say without a doubt, it is the most unstable platform I've used in nearly 30 years of using computers.  Most apps crash routinely, usually while at least one other app is running in the background.  Unloading the crashed app from memory and reopening uually works, but is a huge nuisance (and reason enough to me why iPads are not business-ready, except for specific task applications requiring mobility).  As one trained in both software and systems engineering, with 20 years IT experience mostly in engineering, I have to conclude that IOS app developers use "code and fix" development, with little testing before release.  Of course, in theory it could be that IOS itself isn't well designed to handle multitasking and doesn't provide adequate process isolation.  Either way, it makes for a frustrating experience as a user.
    Has anyone else had similar issues?  Thoughts on why?

    The original iPad does poorly with multiple apps open, the memory is just too small at 256 MB.  The processor is very slow compared to those in the current generation iPads.  And then couple that with developers who are for the most part independent of Apple and merely submit there products to Apple and you get a totally unpoliced set of apps.  Some are true professionals and follow very good programming practices, one that comes to mind is the GoodReader PDF reader.  Very stable and very powerfully built.  then you get into the gamers and Is is almost like they never heard of writing effecient, compact code.
    The issue I see is a tightly controled operating system, with app developers handed a set of specs under which to code, but no real controls other than does the app run and is it free of malicious code.
    Just some thoughts.

  • A question about Object Class

    I got a question about Object class in AS3 recently.
    I typed some testing codes as following:
    var cls:Class = Object;
    var cst:* = Object.prototype.constructor;
    trace( cls === cst); // true
    so cls & cst are the same thing ( the Object ).
    var obj:Object = new Object();
    var cst2:* = obj.constructor.constructor;
    var cst3:* = obj.constructor.constructor.c.constructor;
    var cst5:* = Object.prototype.constructoronstructor;
    var cst4:* = Object.prototype.constructor.constructor.constructor;
    var cst6:* = cls.constructor;
    trace(cst2 === cst3 && cst3 === cst4 && cst4 === cst5 && cst5 === cst6); //true
    trace( cst == cst2) // false
    I debugged into these codes and found that cst & cst2 had the same content but not the same object,
    so why cst & cst2 don't point to the same object?
    Also, I can create an object by
    " var obj:Object = new cst();"
    but
    " var obj:Object = new cst2();"
    throws an exception said that cst2 is not a constructor.
    Anyone can help? many thanks!

    I used "describeType" and found that "cst2" is actually "Class" class.
    So,
    trace(cst2 === Class); // true
    That's what I want to know, Thank you.

  • Best Practices: Question about Passing DataSet to Crystal through C#

    I have used the tutorial provided by Business Objects and have successfully passed a dataset from C# code to Crystal Reports.
    I have a few questions about "best pratices" though.
    It appears that when passing the dataset to crystal then you no longer have the ability to put SQL Expressions in the report anymore otherwise errors will occur.
    So, I'm trying to come up with a way to have a custom field in the SELECT statement and have it show up on the report as a field. So, in the below example I created a custom SQL field called TIMES7 in the query.
    "Select CLM_ID, CLM, PAID_111X, *(PAID111X * 7) As TIMES7*_ From WIKI.MULCRICKET WHERE CLM_ID < 5"
    If I create a formula field in Crystal and set it's value to {MULCRICKET .TIMES7} then it works like a hybrid SQL Expression at run-time.
    This does work but has issues because the database field doesn't really exist in the design environment which causes error when the formula is saved. But it does work at run-time.
    I was wondering if their was a best practice for this?

    So why are you using a formula that doesn't work? If it errors in the designer it's telling you it's not supported.
    Drop the formula into a filed and hide it if you don't want it displayed, this way it gets into the record selection formula.
    "Best Practices" is don't use formulae that won't verify in the Designer. "If it doesn't work in the designer it won't work in code"
    If you need to add an "unknown" field at run time then use RAS to insert the field.

  • Question about multiple class files

    I just started learning JAVA a couple of days ago and the first program I wrote had two classes in one file. here is the program :
    class fib_num {
    public int value;
    public boolean is_even;
    class Fibonacci {
    /** Print the Fibonacci sequence for values < MAX and mark even numbers with an asterick */
    private static final int MAX = 50;
    private static final String Title = "The Fibonacci sequence for values less than " + MAX + ":";
    private static fib_num[] fib = new fib_num[MAX];//This is actually an array of object
    //references to objects of the fib_num class
    public static void main(String[] args) {
    System.out.println(Title);
    //We must initialize each element of the array also !!!!
    for (int i = 0; i < fib.length; i += 1) {
    fib = new fib_num();
    int lo = 1, hi = 1;
    fib[0].value = lo;
    fib[0].is_even = false;
    fib[1].value = hi;
    fib[1].is_even = false;
    for (int i = 2; i < fib.length; i += 1) {
    //create the next Fibonacci number and then save the previous Fibonacci number
    hi = lo + hi;
    lo = hi - lo;
    fib.value = hi;
    //now indicate if the Fibonacci number is even/odd
    if (fib.value % 2 == 0) {
    fib.is_even = true;
    }else {
    fib.is_even = false;
    print (fib);
    //This method prints an array of Fibonacci numbers
    public static void print(fib_num[] array) {
    if (array == null || array.length == 0)
    throw new IllegalArgumentException();
    String mark;
    for (int i = 0; array.value < MAX; i += 1) {
    if (array.is_even) {
    mark = "*";
    }else {
    mark = "";
    System.out.println((i + 1) + ": " + array.value + mark);
    I ran the program and everything went fine. But today I started to write another program with two classes. However the file will not compile and I get an error about interfacing or something. here is the program:
    Note: it's not nearly complete.
    class enumerate {
    //print out all permutations of a list of integers
    public static final int MAX = 4;
    public static int[] initialize(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
    nums = i + 1;
    return nums;
    public static void print(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
    System.out.print(nums);
    System.out.println("");
    public static void swap (int[] nums, int i, int j) {
    int temp = nums;
    nums = nums[j];
    nums[j] = temp;
    public static void main (String[] args) {
    int[] list = new int[MAX];
    list = initialize(list);
    PermutationGenerator x = new PermutationGenerator(5);
    // Systematically generate permutations.
    import java.math.BigInteger;
    public class PermutationGenerator {
    private int[] a;
    private BigInteger numLeft;
    private BigInteger total;
    // Constructor. WARNING: Don't make n too large.
    // Recall that the number of permutations is n!
    // which can be very large, even when n is as small as 20 --
    // 20! = 2,432,902,008,176,640,000 and
    // 21! is too big to fit into a Java long, which is
    // why we use BigInteger instead.
    public PermutationGenerator (int n) {
    if (n < 1) {
    throw new IllegalArgumentException ("Min 1");
    a = new int[n];
    total = getFactorial (n);
    reset ();
    // Reset
    public void reset () {
    for (int i = 0; i < a.length; i++) {
    a = i;
    numLeft = new BigInteger (total.toString ());
    // Return number of permutations not yet generated
    public BigInteger getNumLeft () {
    return numLeft;
    // Return total number of permutations
    public BigInteger getTotal () {
    return total;
    // Are there more permutations?
    public boolean hasMore () {
    return numLeft.compareTo (BigInteger.ZERO) == 1;
    // Compute factorial
    private static BigInteger getFactorial (int n) {
    BigInteger fact = BigInteger.ONE;
    for (int i = n; i > 1; i--) {
    fact = fact.multiply (new BigInteger (Integer.toString (i)));
    return fact;
    // Generate next permutation (algorithm from Rosen p. 284)
    public int[] getNext () {
    if (numLeft.equals (total)) {
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;
    int temp;
    // Find largest index j with a[j] < a[j+1]
    int j = a.length - 2;
    while (a[j] > a[j+1]) {
    j--;
    // Find index k such that a[k] is smallest integer
    // greater than a[j] to the right of a[j]
    int k = a.length - 1;
    while (a[j] > a[k]) {
    k--;
    // Interchange a[j] and a[k]
    temp = a[k];
    a[k] = a[j];
    a[j] = temp;
    // Put tail end of permutation after jth position in increasing order
    int r = a.length - 1;
    int s = j + 1;
    while (r > s) {
    temp = a[s];
    a[s] = a[r];
    a[r] = temp;
    r--;
    s++;
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;
    I thought the error had somethin to do with only having one class per .java file since the compiler creates a .class file. But how come my first program had two classes and it was OK. Is it b/c the second class was merely a collection of fields, almost like a simple struct in C?
    Any help would be appreciated. Thanks

    Move the import java.math.BigInteger line to the start of the file.
    Use the "[ code ] [ /code ]" tags around your code when you post, it makes reading it a lot easier.

  • General programming practice question (possibly re: clusters)

    I apologize for this probably being an old topic or something I should have found elsewhere, but I simply didn't know what to search for.
    I am tackling my first labview program of significant scale, and quickly discovering that the difficulty of wiring scales exponentially with the number of things you're trying to do.  I marvel at the short and sweet pieces of code people post on here, and try my hardest to replicate the style to no avail.
    If I've missed a good guide for good organizational practices when programming, please point the way!
    Essentially, I'm grabbing info from a video signal via a daq card, using this to compute the location of objects in the video, and sending instructions to a robot to control its movement-- this means I have the image wires, serial wires, integer wires for pixel values, real wires for coordinates coordinates, and error wires flying around.  It's not an extraordinary amount of data but it seems to be an extraordinary amount of scooting things around to make things look pretty and/or readable, every time I make a change.
    Clearly use of subVIs is the way to go for each of the tasks, but I still have several pieces of data that need to be communicated from each task to the next.
    Is it common practice to cluster the data even if it's unrelated, just to simplify the wiring?  Is there significant overhead if you're unclustering and re-clustering it in each subVI?  (I tried to write a quick benchmark program but I couldn't quite figure out how to use the profiler)
    Any general veteran tips would be much appreciated!

    Check out the following links: -
    http://www.bloomy.com/resources/index.php#pres
    Specifically here the Powerpoint presentations (five_techniques_for_better_labview_code.pps)
    Some additional pointers/ resources below: -
    http://forums.ni.com/ni/board/message?board.id=LVETF&message.id=1
    http://zone.ni.com/devzone/cda/tut/p/id/4434
    http://openg.org/tiki/tiki-index.php?page=Style%20Guide
    There is a host of other information out there as well, try Google and use the term 'LabView style guide'.
    Hope this helps put you on the right track.

  • Question about inner class - help please

    hi all
    i have a question about the inner class. i need to create some kind of object inside a process class. the reason for the creation of object is because i need to get some values from database and store them in an array:
    name, value, indexNum, flag
    i need to create an array of objects to hold those values and do some process in the process class. the object is only for the process class that contains it. i am not really certain how to create this inner class. i tried it with the following:
    public class process{
    class MyObject{}
    List l = new ArrayList();
    l.add(new MyObject(....));
    or should i create the object as static? what is the benifit of creating this way or static way? thanks for you help.

    for this case, i do need to create a new instance of
    this MyObject each time the process is running with a
    new message - xml. but i will be dealing with the case
    where i will need a static object to hold some
    property values for all the instances. so i suppose i
    will be using static inner class for that case.The two situations are not the same. You know the difference between instance variables and static variables, of course (although you make the usual sloppy error and call them static objects). But the meaning of "static" in the definition of an inner class is this: if you don't declare an inner class static, then an instance of that inner class must belong to an instance of its containing class. If you do declare the inner class static, then an instance of the inner class can exist on its own without any corresponding instance of the containing class. Obviously this has nothing to do with the meaning of "static" with respect to variables.

  • Question about abstract classes and instances

    I have just read about abstract classes and have learned that they cannot be instantiated.
    I am doing some exercises and have done a class named "Person" and an abstract class named "Animal".
    I want to create a method in "Person" that makes it possible to set more animals to Person objects.
    So I wrote this method in class Person and compiled it and did not get any errors, but will this work later when I run the main-method?
    public void addAnimal(Animal newAnimal)
         animal.add(newAnimal);
    }Is newAnimal not an instance?

    Roxxor wrote:
    Ok, but why is it necessary with constructors in abstract classes if we don�t use them (because what I have understand, constructors are used to create objects)?Constructors don't create objects. The new operator creates objects. An object's c'tor is invoked after the object has already been created. The c'tors job is to initialize the newly-created object to a valid state. Whenever a child object is created, the parent's c'tor is run before the child's c'tor, so that by the time we're inside the child's c'tor, setting up the child's state, we know that the parent (or rather the "parent part" of the object we're initializing) is in a valid state.
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Examples for good programming practice with multiple DAQmx tasks

    I'm writing a program to continuously log data from 8 counters, 8 encoders, and 8 voltages. The proof of concept VI with a single counter was simple and elegant, but scaling up to all signals resulted in a wiring mess. I've been working through the Labview Core courses, and am currently on Core 3. I still haven't come across a discussion on how to work with multiple DAQmx tasks without making a mess of the block diagram. Can anyone point me in the right direction?
    Also, say I have a state machine that has a configure, idle, and logging states. I need to set the initial values of the encoders during configuration, and keep up with their changes while in the idle state so I have appropriate starting values when entering the logging state. Can anyone point to an example that shows how this might be accomplished?
    Thanks

    I'm very familiar with AE's/Functional Globals - but I have struggled in the past with handling multiple DAQmx tasks - particularly when you're using multiple devices and using different types of measurements which require seperate tasks/handling (e.g. such as thermocouples which require extra compensation).
    I'm not even sure I know whare the requirements are for needing multiple tasks - I know you can need multiple tasks for a single device if the type of measurement is different but can you share an Analogue Input task amongst multiple devices?
    I think in hindsight (and without too much thought now) it looks like a good case for Object Oriented LabVIEW - with a base DAQmx class (initialise, configure, start, acquire, stop, close etc.) and then child classes for each type of measurement (with one task associated with each - and private data unique to that specific class). You then hold an array of objects (one for each task) and iterate through each one with dynamic despatch to get the data.
    I don't know your particular experience level of using LabVIEW (and as such, OO may not be appropriate) - but as a wider discussion of 'best practice' it seems like an appropriate method I would use going forward.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • Question about multiple classes and Linked Lists

    Lets say you have 4 classes: LinkedList which is the main class, Node, Card, and Hand. im not putting any constructors yet
    The card class keeps track of a card such as a king of diamonds:
    public class Card {
    string suit;
    string rank;
    the node class has a Card object and another node object so it would be
    public class Node {
    Card c;
    Node next;
    the hand class keeps track of the users hand. This program will ask the user if they want to add, remove, print out the hand, or print out the score of the hand, I guess it would be like this
    public class Hand {
    Node head;
    The linkedlist class will contain all the methods for doing the above
    now my questions are. Lets say I want to add a card, so I would have to add a new Node which contains the card. If i wanted to access the new nodes card contents, lets call this node g, can i do, g.c.suit and g.c.rank in which this case c is the card object in Node. Also, these are not going to be nested classes, they are going to be 4 seperate classes, if I declare all variables as private will I need to extend the classes or not and if there is a better way, let me know. Thanks alot for all your help and previous help.

    here is an example of Card and Hand ...
    not saying its good design
    but it does work
    public class Cards {
    public static void main(String[ ] args) {
    Card c1 = new Card ("ace", "diamonds");
    Card c2 = new Card ("two", "spades");
    Card c3 = new Card ("three", "hearts");
    Hand a1 = new Hand ();
    a1.add(c1);
    a1.add(c2);
    a1.add(c3);
    System.out.println("\nshowing hand ...");
    a1.show();
    System.out.println("\ndeleting " + c2.num + " " + c2.suite);
    a1.del(c2);
    System.out.println("\nshowing hand ...");
    a1.show();
    } // main
    } // class
    class Hand exists in 3 states
    and is designed to be a chain of cards ...
    1. when class Hand is first created
       a. it has no card
       b. and no nextHand link
    2. when somecard is added to this Hand
       a. it has a card
       b. and the nextHand link is null
    3. when somecard is attempted to be added to this Hand
       and it already has a card
       then a nextHand is created
       and the somecard is added to the nextHand
       a. so the Hand has a card
       b. and the Hand has a nextHand
    class Hand {
    public Card acard;
    public Hand nextHand;
    public Hand () {
      acard = null;
      nextHand = null;
    public void add (Card somecard) {
      if (acard == null) {
        acard = somecard;
        return;
      if (nextHand == null) nextHand = new Hand();
      nextHand.add (somecard);
    delete this Hand by making this Hand
    refer to the next Hand
    thus skipping over this Hand in the nextHand chain
    for example, removing Hand 3 ...
    1  -  2  -  3  -  4   becomes
    1  -  2  -  4
    public void del (Card somecard) {
      if (acard == somecard) {
        if (nextHand != null) acard = nextHand.acard;
        else acard = null;
        if (nextHand != null) nextHand = nextHand.nextHand;
        return;
      nextHand.del(somecard);
    public void show() {
      if (acard == null) return;
      System.out.println(acard.num + " " + acard.suite);
      if (nextHand != null) nextHand.show ();
    } // class
    class Card {
    public String num;
    public String suite;
    Card (String num, String suite) {
      this.num = num;
      this.suite = suite;
    } // class

  • Question About Runtime Class Not Found Exception

    Good Morning!
    I have a very simple test class that I am using to debug a class loader issue with log4j. I can compile my class. I put the class in a jar file with a manifest that points to the class with the main method. The log4j .jar file is in the .\lib directory, below the test1.jar file. I have fussed around with different variations of -cp & -classpath, without success. I can not figure out why the runtime environment can not load the org.apache.log4j.Logger class.
    What is wrong with the way that I am setting up the runtime environment?
    Thank you!
    ==========================
    source:
    import org.apache.log4j.Logger;
    public class Test1 {
        static Logger logger = Logger.getLogger(Test1.class);
        public static void main(String[] args) {
            System.out.println("Hello World");
    }===========================
    compilation:
    X:\test>javac -classpath .\;.\lib\log4j-1.2.14.jar Test1.java
    jar:
    X:\test>jar -cvmf .\META-INF\MANIFEST.MF test1.jar .\*.class
    added manifest
    adding: Test1.class(in = 627) (out= 380)(deflated 39%)
    MANIFEST.MF:
    Manifest-Version: 1.0
    Created-By: 1.5.0_11 (Sun Microsystems Inc.)
    Main-Class: Test1
    ==========================
    .\lib:
    X:\test>dir .\lib
    Volume in drive X is Storage
    Volume Serial Number is 5871-E6FF
    Directory of X:\test\lib
    11/25/2009 10:19 PM <DIR> .
    11/25/2009 10:19 PM <DIR> ..
    11/25/2009 10:05 AM 367,444 log4j-1.2.14.jar
    1 File(s) 367,444 bytes
    2 Dir(s) 27,042,570,240 bytes free
    X:\test>
    run:
    X:\test>java -client -classpath .\;.\lib\log4j-1.2.14.jar -jar test1.jar
    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Logger
    at Test1.<clinit>(Test1.java:6)
    Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    ... 1 more
    Could not find the main class: Test1. Program will exit.
    X:\test>

    Fussing around with the -classpath parameters won't do anything, because they are ignored when the -jar parameter is present. Running an executable jar means that you specified the classpath in the jar's manifest. Which you didn't do. You need a Class-Path entry in the manifest which provides the path to the log4j.jar file relative to your executable jar.

  • Good programming practice

    There are 2 sets of code which I extracted from a dummy book. The author just want to illustrate 2 ways that we can capture an exception.
    Code set 1_
    import static java.lang.System.out;
    class GoodNightsSleepA {
        public static void main(String args[]) {
            out.print("Excuse me while I nap ");
            out.println("for just five seconds...");
            takeANap();
            out.println("Ah, that was refreshing.");
        static void takeANap() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                out.println("Hey, who woke me up?");
    Code set 2_
    import static java.lang.System.out;
    class GoodNightsSleepB {
        public static void main(String args[]) {
            out.print("Excuse me while I nap ");
            out.println("for just five seconds...");
            try {
                takeANap();
            } catch (InterruptedException e) {
                out.println("Hey, who woke me up?");
            out.println("Ah, that was refreshing.");
        static void takeANap() throws InterruptedException {
            Thread.sleep(5000);
    }To u guys who are experienced java programmer out there. Which set of code do u think is better coding practice and u'll usually code that way ? I personally would say GoodNightsSleepA is a better practice. Or u guy have some other better suggestion ? Thank you.

    Thank you to everybody who responded to this thread. Can anyone pls point me to a link that talks about proper OOP system analysis and design. I believe I need some foundation on this, otherwise I can't write a proper scalable code. Like some of u has pointed that the GoodNightsSleepB class will be more appropriate coz it provides flexibility to other user who would like to use it as a subclass. I didn't thought of this b4 until u guys have enlighten me.
    To corlettk, I'm totally new to AOP. I just read some of the links from the google search result. I'm still in a very blur stage about AOP. Am I right to assume that we should only code to include basic business requirement functions(primary task) in our class and make use of AOP to do the secondary task(such as data verification/exception capturing) ? Pls correct me if I'm wrong. Thank you in advance, guys.

  • Question about a Class loading error

    how can we obtain to reduce the size of classes throughout run time as the source code of my project alone is about 8 MB and this is too heavy for a me program.
    so anybody has any suggestions?

    I see thanks.
    Did you consider keeping that data outside of device (at some web server)? That way, MIDlet would be installed without it and later would download the data from web. Download, in turn, can be done either every time it is needed, or once at MIDlet first launch - in the latter case, downloaded data could be stored in rms for next time it is needed.
    Another idea that comes to mind is to keep data in "auxiliary" MIDlet(s) in different suite(s). That way, again, "main" MIDlet would be installed without it but there will be need to install "auxiliary" MIDlet suites with data. In order to provide data access for "main" MIDlet in other suite, the auxiliary MIDlet would need to run and store the data in a shared-access record store - that is, in store created with [AUTHMODE_ANY access parameter|http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/rms/RecordStore.html#AUTHMODE_ANY].

Maybe you are looking for

  • Help with adding new contacts to BB 8330 - Cellular South

    Can someone help me, please?  I'm new to Blackberry, but my boss has just gotten one.  How can I add contacts (I have quite a few to get into this new phone) without having to manually enter them on the phone?  I'd prefer to compile a list on my comp

  • Open a webi report from a Dashboard components

    Hi All, I have created a dashboard using Dashboards 4.0.It has a bar chart,line chart,combination chart.all these chart on X-Axis have month names as dimensions and y - axis shows different measures. So now the requirement is the user wants to select

  • Which version of Airport Express do I have?

    Hi -- We just moved into a new place and we're having some trouble getting the wireless network to reach all the corners of the house. I have an old Airport Extreme that is helping somewhat but not great so I am considering upgrading our Time Machine

  • Networking Windows to Mac OS X 10.4.5

    I am really sorry to ask a question that I bet has been asked 100's of times here. I'm failing completely in getting my Windows XP machine to talk to my Mac OS X machine. Believe me I've surfed and surfed, read docs that I could find, looked at help

  • Xcelsius - QaaWS

    Guru's I have Crystal Xcelsius &  QaaWS . I developed Dashboard using Xcelsius as well as pulling the data from database by QaaWS . In Xcelsius I am plugging the QaaWS data by Data-Connections-plugging WSDL url as well as placing input / output value