Question about handing classes in Objective-C

Greetings -- I'm pretty new to Objective-C. I do have a few apps out in the app store, but they were simple one-form apps where I was able to dump everything into the main class and be happy with it.
This new project I'm working on, is huge in comparison. Over 25 views, accessible through TableView driven menus.
I was able to get all of the menus working, each launching a separate view NIB file (so far, just a label to show me that it's done, but I got that part working.)
Now what I'm trying to do, is add a "click" sound when a row is selected. But I'm wanting to do this in a separate class, so each .m file can instantiate it's own version of the logic instead of having the same code 29 times.
So, this is what I've done:
Click.h
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
@interface Click : NSObject
SystemSoundID soundID;
-(void) playClick;
@end
Click.m
#import "Click.h"
@implementation Click
-(id) init
self = [super init];
NSString *path = [[NSBundle mainBundle] pathForResource:@"click" ofType:@"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
return self;
-(void) playClick
AudioServicesPlaySystemSound (soundID);
@end
RootViewController.h
#import <UIKit/UIKit.h>
#import "Click.h"
@interface RootViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
NSArray *controllers;
Click *clicker;
@property (nonatomic, retain) NSArray *controllers;
@property (nonatomic, retain) Click *clicker;
@end
RootViewController.m
#import "RootViewController.h"
@implementation RootViewController
@synthesize controllers, clicker;
- (void)viewDidLoad
Click *newClicker = [[Click alloc] init];
clicker = newClicker;
[newClicker release];
self.title = @"Main Menu";
- (void)dealloc {
[controllers release];
[clicker release];
[super dealloc];
#pragma mark Table View Delegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
[clicker playClick];
I cut out the code pieces regarding the TableView that I know works, and tried showing only the parts that I've added to make the sound.
What I've tried, is when the RootViewController is created, it has a SystemSoundID type variable defined with it named clicker. Then as part of "viewDidLoad", instantiate an instance of the class and have it automatically populate the variable "soundID". Then during "didSelectRowAtIndexPath", I want the "playClick" method of "clicker" to be run, but at this point the app seems to get caught in some sort of perma-loop, and I have to "STOP"/"Home" out of it.
I'm hoping the problem is my rookie-status at using Objective-C objects, and the solution jumps out at you veterans, and then whatever problem I am having won't be duplicated when I create additional classes that I'd want to merge into my ViewController logic.
Hope I've made everything clear. If anyone has questions, I'll be checking for replies
Thanks.

Dragon's Nest wrote:
Is it preferred to init a copy and assign it like you did above?
Yes, it's an accepted pattern which you'll see in most of the sample apps. Asnor's code works just as well in this case, and it might always work for you if you stick to that same pattern. However if you were working on a team and everyone else used the more common pattern it might cause a problem. For example, this code would cause a memory leak:
@property (nonatomic, retain) Click *clicker; // interface
self.clicker = [[Click alloc] init]; // implementation
The above is the flip side of your original code. In this case, because we're not releasing the newly alloced object, its retain count is +2 after the setter retains it.
There are other advantages to the accepted pattern. Suppose you weren't assigning the new object to an ivar but only using the object in that one block of code. Should you then release it? Yes. Will you remember? Well, if you're using the pattern, you'll always release it. If you always release the local pointer regardless of whether it gets retained elsewhere, you're much less likely to have a memory leak. How bout the case where you return the pointer (i.e. alloc an object and return it's address from that method)? In that case you just autorelease it. So whoever called the method needs to retain the returned object if it needs to be used after the current event cycle.
Either way, immediate release or autorelease, you're always releasing an alloced object in the same block of code.
Memory management can easily get out of control without following consistent patterns. Alloc->retainBySetter->release is the accepted pattern for Cocoa. Your original code meant to use the correct pattern, but you just forgot that clicker=object isn't the same as self.clicker=object because the latter retains the object. Once you've consistently used the correct pattern for awhile, you'll almost never make that mistake.
Also, is there any difference in calling it in the following two ways:
@property (nonatomic, retain) Click *clicker; // <-- must be considered to answer this question
@synthesize clicker;
[clicker playClick];
[self.clicker playClick];
In the above case there's no difference since the getter synthesized for that property declaration will simply return the value of the ivar (i.e. the address of the retained Clicker object). But in the general case, there certainly could be a difference. If the property was atomic, for example, the results could be different. Of course there will definitely be a difference if you wrote a custom getter that did something more than the default.
Is there a rule or convention re when to use the getter and when to use the ivar directly? Not that I know of. I think you just need to be aware of what the getter does when deciding whether to use the dot notation. This is a point you might want to research a little more, though. Maybe someone here with more experience in Obj-C or Cocoa will comment.
In fact a few of the experts in this forum advise against ever using dot notation. They feel it was invented to crash newbie programs. If you never use dot notation the difference between these two lines is much easier to see:
clicker = newClicker;
[self setClicker:newClicker];
But once again, if you stick to the same pattern all the time, it's much harder to make a mistake.
- Ray

Similar Messages

  • 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 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.

  • Question about SWING and ActionEvent Object.

    When using a graphical component like a JButton,
    one typically adds an ActionListener Object to that button using the
    addActionListener method,
    in order for a click/appropriate action to execute desired Java code.
    One's desired code is within one's own ActionListener Object,
    which implements an appropriate interface and the equivalent of
    that interface's actionPerformed method.
    -How does one program one's own ActionEvent Object,
    and register that object (myActionEvent) with the java virtual machine
    such that your OWN event object is fired, instead of the
    default action?
    -Does instantiating one's appropriate ActionEvent object
    "fire" it as an event?

    Zac1234 wrote:
    When using a graphical component like a JButton,
    one typically adds an ActionListener Object to that button using the
    addActionListener method,
    in order for a click/appropriate action to execute desired Java code.Only for components that accept ActionListeners of course. This won't work with a JLabel for instance or any random "graphical component".
    -How does one program one's own ActionEvent Object,
    and register that object (myActionEvent) with the java virtual machine
    such that your OWN event object is fired, instead of the
    default action?Please explain exactly what you're trying to do here. Perhaps it's just me, but I'm not sure I understand what you mean by programming your own ActionEvent Object. An ActionEvent object can be simply created like any other object and by using the appropriate constructor (the API can help), but I don't think that you're talking here about ActionEven objects -- the parameter of the actionPerformed method, are you? Please give details as they are important here.
    -Does instantiating one's appropriate ActionEvent object
    "fire" it as an event?No, but again I'm stumped as to exactly what you're trying to do here.
    Finally, let's keep this discussion here, but next time, you will probably want to ask your Swing questions in the Swing forum.
    Best of luck.

  • 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.

  • Question about PickMouseBehavior class

    Hello, I wrote yesterday in this forum, but now my problem is other. I'm doing a extension of PickMouseBehavior class, but I want that these class is only activated with a specific mouse button or when I passing the mouse over determinated Box element(Box is my branchgroup for the PickMouseBehavior class).
    How can I do it?? I think that I have to redefine the initialize and processStimulus methods, but I don't know how can I do it. Anybody can help me please??
    Sorry about my bad english.
    Thanks

    i think is in the Class class. I'm not so sure as don't have the API on this machine. You can get the class from every object from the getClass() method, then call the getResource() or getResourceAsStream() i can't really remember...

  • Two questions about defining class, pls help me

    Hi, guys. I'm green hand and here are two questions puzzled me several days.
    We know such example as below is a case of cyclic inheritance
    class Base extends Base{     
    But I can't figure out why below is a case of cyclic inheritance too
    class Base{
    class Derived extends Base{
    class Base{
    I can't find the clue of cyclic inheritance. It's quite different from the case that a class extends itself or its subclass.
    Another question is why the inner class can't have the same name of outer?
    class Base{
    class Base{          
    The compiler says Base is already defined in unnamed package. As it says, the inner class is defined in the
    unnamed package, but we know below is correct.
    class Base{
    class Basic{          
    class Derived {
    class Basic{
    We know it's correct. But as the compiler says above, the different two inner class Basic are both defined in the
    unnamed package. Why it's valid and why above is invalid?

    Hi,
    Can you tell us which product (s) you are referring to ? Can you also tell us the nature of your business requirements so that we can offer some suggestions ?
    Regards,
    Sandeep

  • Question about Math Class

    I have a couple of Java questions I was wondering if anyone could answer:
    1). In this one statement, which takes the greatest common denominator and places it in the variable commom:
    int common = gcd (Math.abs(numerator), denominator);
    A).What is gcd? I looked it up and it's not a reserved word in the math class. In the class that this statement comes from there is no variable, object, or method named gcd. There is also no gcd variable, object, or invoked method in the client code that uses the class that this statement comes from.
    B ). I know that abs is a method of the math class for the absolute value of a number(in this case the number inside the variable numerator.). And I know that when the abs method is invoked it sends the variable 'numerator' as the parameter for the data to take the absolute value of. What I don't understand is the syntax of this statement in regards to how you can take the absolute value of the variable 'denominator' haveing a variable 'numerator' inclosed in the parenthesis and simpley adding a comma to include the variable 'denominator' in the argument to be sent in the invocation of the abs method. It seems like this would be the correct syntax:
    int common = (Math.abs(numerator))/(Math.abs(denominator));
    Can anyone explain the 'int common = gcd (Math.abs(numerator), denominator);'
    statement?
    Thanks,
    -dman

    > A).What is gcd?
    As already been said: it's the Greatest Common Divider.
    Example: fraction 9/24, then gcd(9, 24) == 3.
    >It seems like this would be the correct syntax:
    int common = (Math.abs(numerator))/(Math.abs(denominator));
    Probably the gcd(...) method is used to normalize a fraction whose denominator is always positive. If the fraction is smaller then zero, the numerator is negative. And to caculate the Greatest Common Divider of two numbers, the gcd(...) method needs two positive arguments.
    Google for "Euclid GCD algorithm".

  • Newbie question about entity and view objects

    Hi everyone,
    My first ADF application in JDeveloper is off to a difficult start. Having come from a forms background, I know that it is necessary avoid using post-query type lookups in order to have full filtering using F11/Ctrl+F11. This means creating an CRUDable view and getting as much of the lookup data as possible into the view without losing the ability to modify the data. In JDeveloper, I do not know how to build my data model to support that. My thought was to start with a robust updateable view as my main CRUD EO and then create a VO on top of that with additional EOs or VOs. But, I have found that I cannot add VOs to another VO. However, if I link the VOs then I have a master-detail which will not work for me.
    For example, I have two joins to CSI_INST_EXTEND_ATTRIB_V shown in the queries below and need to have that show in the table displaying the CRUD VO’s data. It seemed that the best way to do this is to create a CSI_INST_EXTEND_ATTRIB_V entity object and view object. The view object would have two parameters, P_INSTANCE_ID and P_ATTRIBUTE name. Both the building and the unit are needed on the same record, and this is not a master-detail even though it might look that way. (A master-detail data control will not work for me because I need all this data to appear on the same line in the table.) So, I need help figuring out the best way to link these to the main (CRUD) view; I want as much of this data as possible to be filterable.
    select
    cieav.attribute_value
    from
    csi_inst_extend_attrib_v cieav
    where cieav.instance_id = p_instance_id
    and cieav.attribute_code = 'BUILDING NAME'
    select
    cieav.attribute_value
    from
    csi_inst_extend_attrib_v cieav
    where cieav.instance_id = p_instance_id
    and cieav.attribute_code = 'UNIT NAME'
    Ultimately, I need to display a ton of data in each record displayed in the UI table, so a ton of joins will be needed. And, I need to be able to add records using the UI table also.
    James

    Hi Alejandro,
    Sorry if I caused confusion with my first post. What I had in mind assumed that I could have a single CSI_INST_EXTEND_ATTRIB_V EO with a BuildingVO and UnitVO on top of it. So, I wrote the queries individually to show how I would invoke each view. When I realized that confused the issue, I rewrote the query to explain things better.
    Now having seen your 2 queries. You need to create 2 EO. One for each table. Then create an association between the 2 aeO (this will be the join you are talking about). Then, you need to create a VO based on one of the EO and after you can modify and add the second EO (in here you select the join type).
    After your done with this, youll have 1 VO that supports CRUD in both tables.
    There were three tables in the query: CIEAV_BUILDING, CIEAV_UNIT, and T -- the main CRUD table. When you say that I should create two EOs, do you mean that they are to be for CIEAV_BUILDING and CIEAV_UNIT? Or, CIEAV and T? Assuming CIEAV and T, that sounds like it would allow me to show my building or unit on the record but not both.
    By the way, everything is a reference except for the main CRUD table.
    Look forward to hearing from you. Thanks for your help (and patience).

  • A question about calling classes

    Hi,
    I have a question regarding software design so that each class is independent of other.
    public class A
        public void methodA()
                 B m_B=new B();
              String strA=m_B.getBString();
              System.out.println(strA);
    public class B
       public String getBString()
                      return "someString";
    }My question: Is it possible to call the method in class B from class A without creating an instance of class B in method of class A ?
    I am trying to figure out if this can be done using interfaces and abstract classes.
    I am waiting for some suggestions and if you have completely different suggestion then I am open for it too.
    thanks in advance,
    @debug.

    interface I {
        String getString();
    class B implements I {
        public String getString() { return "someString";}
    class A {
        private I foo;
        public void setFoo(I foo) {this.foo = foo;}
        public I getFoo() {return foo;}
        public void methodA() {
          System.out.println(getFoo().getString());
    public class Main {
        public static void main(String[] args) {
            A a = new A();
            a.setFoo(new B());
            a.methodA();
    }There's one problem with decoupling A and B in this case - A's method creates an instance of B. The above is one solution. There are many others.

  • (newbie) Question about replacing .class files and web.xml file

    I'm new to servlets and I have two quick questions...
    Do I absolutely need a web.xml file to define all my servlets, or can I simply place .class files into the WEB-INF directory and expect them to run?
    If my application server (for example Tomcat) is running and I replace a servlet .class file, do I need to restart the server for the new .class file to take effect?
    ...or are both of these questions specific to the application server I'm using?

    Hi,
    From an article I read:
    With Tomcat 3.x, by default servlet container was set up to allow invoking a servet through a common mapping under the /servlet/ directory.
    A servlet could be accessed by simply using an url like this one:
    http://[domain]:[port]/[context]/servlet/[servlet full qualified name].
    The mapping was set inside the web application descriptor (web.xml), located under $TOMCAT_HOME/conf.
    With Tomcat 4.x the Jakarta developers have decided to stop allowing this by default. The <servlet-mapping> tag that sets this mapping up, has been commented inside the default web application descriptor (web.xml), located under $CATALINA_HOME/conf:
    <!-- The mapping for the invoker servlet -->
    <!--
    <servlet-mapping>
    <servlet-name>invoker</servlet-name>
    <url-pattern>/servlet/*</url-pattern>
    </servlet-mapping>
    -->
    A developer can simply map all the servlet inside the web application descriptor of its own web application (that is highly suggested), or simply uncomment that mapping (that is highly discouraged).
    It is important to notice that the /servlet/ isn't part of Servlet 2.3 specifications so there are no guarantee that the container will support that. So, if the developer decides to uncomment that mapping, the application will loose portabiliy.
    And declangallagher, I will use caution in future :-)

  • A question about Abstract Classes

    Hello
    Can someone please help me with the following question.
    Going through Brian's tutorials he defines in one of his exercises an  'abstract' class as follows
    <ClassType ID="MyMP.MyComputerRoleBase" Base="Windows!Microsoft.Windows.ComputerRole" Accessibility="Internal" Abstract="true" Hosted="true" Singleton="false">
    Now I am new to authoring but get the general concepts, and on the surface of it, it appears odd to have an 'abstract' class that is also 'hosted' I understand and abstract class to be a template with one or more properties defined which is then used
    as the base class for one or more concrete classes. Therefore you do not have to keep defining the properties on these concrete classes over and over as they inherit the properties from their parent abstract class, is this correct so far?
    if the above is correct then it seems odd that the abstract class would be hosted, unless (and this is the only way it makes sense to me) that ultimately (apart from singleton classes) any class that is going to end up being discovered and
    thereby an instance of said class instigated in the database must ultimately be hosted somewhere, is that correct?
    in other words if you has an abstract class, which acts as the base class for one or more concrete classes (by which I mean ones for which you are going to create lets say WMI discoveries ), if this parent abstract class is not ultimately
    hosted to a concrete class of its own then these child concrete classes (once discovered) will never actually create instances in the database.
    Is that how it is?
    Any advise most welcome, thanks
    AAnotherUser__
    AAnotherUser__

    Hi,
    Hosting is the only relationship type that doesn't require you to discover it with a discovery rule. OpsMgr will create a relationship instance automatically for you using a 'hosted' properties 'chain' in a class\model definition. In an abstract class definition
    you need to have this property set to 'true' or you will 'brake' a hosting 'chain'.
    http://OpsMgr.ru/

  • Question about Abstract Classes and Class Inheritance

    The semester is winding down, and the assignments are getting more complicated....
    Prof has given us a project involving both an interface and an abstract class. There's a class Person, then an abstract class Employee that extends Person, and two types of Employees (Hourly and Salaried) that extend Employee. The finished assignment is a type of payroll program that's supposed to be able to store both types of Employees and related info (name, salary, etc). One thing the prof suggested was to store both HourlyEmployees and SalariedEmployees in an array of Employees. But you can't instantiate an array of Employees directly, of course, since it's an abstract class.
    So is it possible to create an array of Persons, cast either HourlyEmployees or SalariedEmployees into Employee objects, and then store the Employee objects in the Person array? And if I do that, can I still use methods particular to the SalariedEmployees and/or HourlyEmployees once they are in the Person array? Or can I store SalariedEmployee and HourlyEmployee directly in an array of Persons, without having to cast them into anything else? (In that case, I'm not sure what the point of having the abstract Employee class is, though). Do they become just generic "Persons" if I do this?
    Thanks for any help!

    But you
    can't instantiate an array of Employees directly, of
    course, since it's an abstract class.Sure you can. You just can't instantiate Employee (the abstact class itself, as opposed to its subclasses) objects.
    Employee[] employees = new Employee[20];
    employees[0] = new HourlyEmployee();That should work.
    So is it possible to create an array of Persons, cast
    either HourlyEmployees or SalariedEmployees into
    Employee objects, and then store the Employee objects
    in the Person array?You could do that as well, but you shouldn't need to cast it.
    Given the type hierarchy you describe, an HourlyEmployee is a Person, so you should be able to assign an HourlyEmployee directly to a Person-valued variable.
    And if I do that, can I still use
    methods particular to the SalariedEmployees and/or
    HourlyEmployees once they are in the Person array?No. If the method doesn't exist in Person, then you can't call it on a Person variable, even if the method does exist in the class implementing Person.
    But if the method exists in Person, but is implemented and possibly overridden in HourlyEmployee, you can still invoke it, by just invoking the Person method.
    public interface Person {
      public void feed();
    public abstract class Employee implements Person {
      public abstract void hire();
    public class HourlyEmployee extends Employee {
    // then:
    Person persons = new Person[20];
    // add HourlyEmployees or SalariedEmployees to persons array...
    persons[0].feed(); // OK!
    persons[0].hire(); // NOT OK!

  • "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.

Maybe you are looking for

  • How do I use my time capsule as a wifi extender and still use as a backup in Time Machine

    I purchased a new airport extreme and want to use my existing time capsule as a wifi extender in another part of the house.  How do I set this up so that I can still use the time capsule as my backup (time machine) hard drive?

  • Importing 32 bits images

    Hello! I'm trying to import a 32bits depth image format using the FBIO sample. I set the depth to 32 with the following instruction ERR(suites.IOInSuite1()->AEGP_SetInSpecDepth(specH, 32)); And the project tab shows me that the image has million of c

  • Advice for scanning my entire life's images

    I am beginning the huge task of scanning the thousands of photos that are my entire life's collection. Disc space is important, but I also want to make sure that I scan the images at a high enough resolution that I will not be upset at the standard I

  • Using Document Library with Baseline

    Hi there, I have a specific need with Sharepoint. I have a document library and I want to be able to mark with a tag or generate a baseline for my folders. I've already searched on the web, and there is someone doing it just coping and pasting every

  • Problem with constant "Allow application to use ne...

    I just bought this phone today (first Nokia phone) and I'm having a pretty irritating issue with the error message: "Allow application to use network and send or receive data?"  This seems to only happen with my Gmail, fring, and eBuddy applications.