Results 1 to 9 of 9
Like Tree6Likes
  • 1 Post By AlexGraal
  • 1 Post By kjkrum
  • 1 Post By AlexGraal
  • 2 Post By gimbal2
  • 1 Post By gimbal2

Thread: Can't understand some basic things - please enlighten me :D

  1. #1
    truely is offline Member
    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0

    Default Can't understand some basic things - please enlighten me :D

    Hello, I'm follow a tutorial and I can't understand some basic things :

    I can't understand why some code works but when I change it it does not (some confusion with "static" and some more basic stuff):

    The working code :
    Java Code:
    public class Hammer {
    
        public boolean destroy(Phone p) {
            p.turnedOn = false;
            p.price = 0;
            System.out.println("BOOM");
    		return false;
        }
        
        public static void main(String[] args) {
        	
            Hammer h = new Hammer();      // Create new hammer object
            Phone phone = new Phone();    // Create new Phone object
            Phone phone2 = new Phone(); // Create Another Phone object
            
            h.destroy(phone);  // Destroy Phone object
            h.destroy(phone2); // Destroy Second Phone object
        }
        
    }
    Now I want to try and change it a bit but it is not working :

    Java Code:
    public class Hammer {
    
        public boolean destroy(Phone p) {
            p.turnedOn = false;
            p.price = 0;
            System.out.println("BOOM");
    		return false;
        }
        
        public static void main(String[] args) {
        	
        	Phone phone = new Phone();
        	Phone phone2 = new Phone();
        	Hammer.destroy(phone);
          	Hammer.destroy(phone2);
        }
        
    }

    It tells me "cannot make a static reference to the non-static method destroy(phone) from the type Hammer".
    Why when I do "Hammer h = new Hammer();" and then "h.destroy(phone);" - then "destroy(phone)" does not need to be static whereas when I do "Hammer.destroy(phone);" it does have to be static?
    (When I change "public boolean destroy(Phone p)" to "public static boolean destroy(Phone p)" everything works)


    Thank you

  2. #2
    AlexGraal is offline Señor Member
    Join Date
    Jan 2014
    Posts
    184
    Rep Power
    0

    Default Re: Can't understand some basic things - please enlighten me :D

    Here is why in a nutshell.

    When you add static, you are saying that in any "instance" of the class, the contents and execution are the same. Therefore, everything should always work/

    However, without the static, you need to create an instance of the class first before you can call on a method in that specific instance.

    AKA, if a method is NOT static, an instance must be created to accent that method.

    When you do,
    Java Code:
    Hammer h = new Hammer();
    You are creating a new instance, now allowing you to reference that specific instance and the methods contained within it - specifically "destroy".
    truely likes this.

  3. #3
    truely is offline Member
    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0

    Default Re: Can't understand some basic things - please enlighten me :D

    Thank you Alex,
    I understand it better now.
    So please tell me if I understood correctly :
    static should be added only if I want to create an instance from inside the same class (Hammer class in this case)?
    And if I want to use the destroy method(that's inside Hammer class) from outside the Hammer class, then it does not have to be static? (or actually shouldn't be static?)

  4. #4
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Can't understand some basic things - please enlighten me :D

    Another way to put is is that static members (fields and methods) are conceptually part of the class itself, not part of instances of the class. So you can call static methods anywhere, but to call a non-static method, you must call it on an instance of the class.
    truely likes this.
    Get in the habit of using standard Java naming conventions!

  5. #5
    AlexGraal is offline Señor Member
    Join Date
    Jan 2014
    Posts
    184
    Rep Power
    0

    Default Re: Can't understand some basic things - please enlighten me :D

    The concepts of Static and not-static took me some example-viewing and some thinking to pick up when I learned them.

    If a method is static, it can be referenced, both from within the same class and from another class. Here is an example.

    Java Code:
    public class test {
       public static void print() {
          System.out.println("It worked!");
       }
       public void otherPrint() {
          System.out.println("This also worked!");
       }
    }
    Java Code:
    public class example { 
       public static void main ( String[] args ) {
           test.print();
       }
    }
    This WILL work, because the method "print" is static in the "class". You don't need to create a specific instance - you can just reference it specifically any time you want, because it is always the same.

    On the other hand, if you tried doing this:
    Java Code:
    public class example {
       public static void main ( String[] args ) {
          test.otherPrint();
       }
    }
    it wouldn't even compile, insisting that "a non-static method can't be referenced from a static method." For non-static methods, you need to create an INSTANCE of that class with a specific name.
    Java Code:
    public class example {
       public static void main ( String[] args ) {
          test x = new test();
          x.otherPrint();
       }
    }
    NOW it'll work.


    You'll use non-static classes when what the class does depends on the instance of the class. I'm not quite sure how to explain it any better.
    Here is a sample from something that I'm working on.
    Java Code:
    public class freqComb<String> {
        private int freq;
        private String chunk;
        public freqComb(int i, String n){
            this.freq=i;                  //the constructor - creates the "parameters" for the instance
            this.chunk=n;
        }
        public int getFreq() {
            return freq;         //returns one of the parameters for the instance
        }
        public String getChunk() {
            return chunk;          //returns the other parameter
        }
    }
    The first method is a constructor. So in my other code, where I'm working on ordering/manipulating these, I would do,
    Java Code:
    freqComb<String> a = new freqComb<String>(7,"a");
    Then, I could call on the methods from this specific instance by doing
    Java Code:
    a.getFreq()
    which would return 7.

    You wouldn't be able t make any of those methods static, because an instance has to be created for anything to have values there - a static method would have no purpose or use.
    truely likes this.

  6. #6
    truely is offline Member
    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0

    Default Re: Can't understand some basic things - please enlighten me :D

    Omg after your explanation I had that feeling you get when you finally understand something after a long time of thinking (my head hurt ) But , I think I now got it!
    so static methods actually do something specific without the ability to actually change them , but simply use them,
    and when you use non-static it's for calling it from somewhere else in order to use it with parameters that you need (using an instance).
    When you're using non-static methods you're actually creating a code that has a use for multiple instances so that you can give each instance its own values.

    *By the way, in your code why your wrote "this.freq=i;" and "this.chunk=n;" ? can't you write it without "this."?

    Last edited by truely; 02-19-2014 at 10:24 PM.

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

    Default Re: Can't understand some basic things - please enlighten me :D

    Quote Originally Posted by truely View Post
    *By the way, in your code why your wrote "this.freq=i;" and "this.chunk=n;" ? can't you write it without "this."?
    Try it and find out! No better teacher than experimentation. No matter what someone in this forum tells you, you'd need to try it out and see for yourself anyway so you might as well go right ahead.

    and when you use non-static it's for calling it from somewhere else in order to use it with parameters that you need (using an instance).
    Be careful with the terminology. Parameters are what you pass to a method and you can do that no matter if the method is static or not. You are referring to object attributes or object properties here (to make it more complicated, there isn't one strict term for it). Here is an example that might help a little:

    Java Code:
    public class World{
      private String name; // attribute/property
    
      private World(String name){ // note how the constructor is private; research what that means
        this.name = name;   // see why 'this' can be useful
      }
    
      public String getName() {
        return name; // works because getName() is not static. 
      }
    
      public static World create(String newWorldName){  // newWorldName = parameter
         return new World(newWorldName);
      }
    }
    
    
    World earth = World.create("earth"); // works, create is static
    System.out.println("Name: "+ earth.getName());  // works
    System.out.println("Name: " + World.getName()); // doesn't work
    AlexGraal and truely like this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    truely is offline Member
    Join Date
    Feb 2014
    Posts
    8
    Rep Power
    0

    Default Re: Can't understand some basic things - please enlighten me :D

    Thank you, it's just a bit hard for me to understand these programming language expression in English because it's not my mother tongue

  9. #9
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

    Default Re: Can't understand some basic things - please enlighten me :D

    Your English is fine so I really don't think that's it; give it time and you'll start to see the Matrix. Meanwhile try to write clearly formatted code with proper named variables to make your life as easy as possible now and later on. And there I will stress: use English for everything, since as you already know the language borrows from English too. You don't want to create a mess of code that is half in your native tongue and half in English, or your brain will be making constant translations where not necessary. That's tiring.

    Note: just generic advice, I'm not accusing you of anything. Just warning you for a common mistake I see people make, I often have to kick people to stop using Dutch variable and method names because they give me an eye infection.
    truely likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. [Help] Basic math program help. A easy to understand thread.
    By MagicalPeppers in forum New To Java
    Replies: 2
    Last Post: 01-06-2013, 05:32 PM
  2. Need help with GUI and integers(just some basic things)
    By Wizard0860 in forum New To Java
    Replies: 1
    Last Post: 12-14-2012, 09:50 PM
  3. Replies: 1
    Last Post: 06-28-2012, 09:08 PM
  4. Can you help me understand this basic GUI concept?
    By EscSequenceAlpha in forum New To Java
    Replies: 1
    Last Post: 04-08-2012, 08:33 PM
  5. XML, and other things.
    By Tortex in forum New To Java
    Replies: 5
    Last Post: 03-28-2010, 05:53 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •