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

Similar Messages

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

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

  • 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 extending classes

    Hi
    I've created my own class that extends javax.swing.JTextField as follows:
    public class myTextField extends javax.swing.JTextField{
         public myTextField(){
              super();
              initialize();
         protected void initialize()
              super.setEditable(false);
              super.setHorizontalAlignment(javax.swing.JTextField.LEFT);
              super.setBorder(null);
              super.setSelectionColor(null);
    }Dunno if this is the best way to do it, but it works, so I'm happy!
    My question is: Is it possible to have more than one definition in this class?
    For example, a myTextField2 that extends JTextField with completly different attributes (eg, different back ground colour etc) or do I have to create a new class?

    For example, a myTextField2 that extends JTextField
    with completly different attributes (eg, different
    back ground colour etc) No, but you can create another constructor that accepts different arguments.
    public myTextField(Color c)Like that. By the way class names should start with an upper-case character.

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

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

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

  • Question about nested classes

    Hi, i currently have the following problem:
    I have 2 classes, one of which also has a nested class:
    1. Home.java (extends JApplet)
    2. Away.java (extends JPanel) has nested class, private class ButtonListener implements ActionListener
    Now in Home.java I have a Vector ( called bankaccount) which i pass to the Constructor of Away.java ( I declared the vector again there as an instance by Private Vector bankaccount;).
    My problem is that in ButtonListener I am trying to access the Vector so that i can modify it when a button has been clicked, and i thought i could just use the commands of bankaccount.add() and bankaccount.get() directly, however it seems like ButtonListener cannot access the Vector, even though i passed it along to the Constructor of the Away class.
    Any suggestions on how i get access the Vector from the ButtonListenere class?

    This is an example:
    public class Home extends JApplet
    private Away away;
    private Vector bankaccount;
    public void init()
         bankaccount = new Vector();
         away = new Away(bankaccount);
    public class Away extends JPanel
    private Vector bankaccount;
    JTextArea text1= new JTextArea(50,50);
    public Away(Vector bankaccount)
       //declare buttons,textarea,setLayout,etc
    button1.addActionListener (new ButtonListener());
    //i can set  text1.setText(( String)bankaccount.get(0));
    // here to access bankaccount, and it shows up fine, but i want
    // do it in from the class below
    private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                         //trying to access bankaccount here by doing:
                        // but it is not doing anything
                        text1.setText(( String)bankaccount.get(0));
    }

Maybe you are looking for

  • Jabber and O365 integration

    Hello, Do we need any additional licenses from Cisco or Microsoft to make a full possible integration between O365 and Jabber ? For example features like : Single Inbox Unified Messaging with SpeechView transcriptions,  Microsoft Word Click to Call,

  • Grouping invoices for payment across orgs

    Hi All, In R12 parables, Is it possible to make a payment of two invoices as below created under two different operating for the same supplier and supplier site using the same payment. (Using a PPR single payment request) ORG_ID VENDOR_ID VENDOR_SITE

  • Why I can not...

    Why I can not open normally PC-made Word-documents in my iMac with AppleWorks 6? Is it possible? I have Mac OS X 10.6.8.

  • Child project opens in new window instead of default window

    I have a windows html help Robohelp 9 project.  When I view the output chm file, I can select items from the TOC and they are displayed in the default window.  I then made this project a child in a master project.   If I open the master CHM and selec

  • Can I get ios6 back, after update to ios7?

    It's to hard to see My calender and the Keyes on the Keyboard, My background photo's docent fit, my headset do not work in TomTom, only when I have a call, but then, I can't stop the app, to stop guidens to interfeair. I believe "Steve" would not let