开发者

How to turn static methods into non-static. Small explanation/examples related to java oop

I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code. The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.) The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code. Thanks in advance for any hints.

    import java.util.Scanner;

/**
 *
 * @author
 */

public class NumberArray2{

    public static int[] table() {
        Scanner Scan = new Scanner(System.in);
        System.out.println("How many numbers?");
        int s = Scan.nextInt();
        int[] tab = new int[s];

        System.out.println("Write a numbers: ");
        for(int i=0; i<tab.length; i++){
           tab[i] = Scan.nextInt();
        }
        System.out.println("");
        return tab;
    }

    static public void output(int [] tab){
        for(int i=0; i<tab.length; i++){
            if(tab[i] != 0)
                System.out.println(tab[i]);
        }

    }

    static public void max(int [] tab){
       int maxNum = 0;
        for(int i=0; i<tab.length; i++){
            if(tab[i] > maxNum)
                maxNum = tab[i];

        }
    //return maxNum;
       System.out.println(maxNum);
    }

    static public void divide(int [] tab){
        for(int i=0; i<tab.length; i++){
            if((tab[i] % 3 == 0) && tab[i] != 0)
                System.out.println(tab[i]);
   开发者_如何学编程     }
    }

    static public void average(int [] tab){
          int sum = 0;
          for(int i=0; i<tab.length; i++)
            sum = sum + tab[i];
            int avervalue = sum/tab.length;
            System.out.println(avervalue);

}




        public static void isPrime(int[] tab) {
        for (int i = 0; i < tab.length; i++) {
            if (isPrimeNum(tab[i])) {
                System.out.println(tab[i]);
            }
        }


    }

    public static boolean isPrimeNum(int n) {
        boolean prime = true;
        for (long i = 3; i <= Math.sqrt(n); i += 2) {
            if (n % i == 0) {
                prime = false;
                break;
            }
        }
        if ((n % 2 != 0 && prime && n > 2) || n == 2) {
            return true;

        } else {
            return false;
        }
    }




    public static void main(String[] args) {
        int[] inputTable = table();

        //int s = table();


        System.out.println("Written numbers:");
        output(inputTable);
        System.out.println("Largest number: ");
        max(inputTable);
        System.out.println("All numbers that can be divided by three: ");
        divide(inputTable);
        System.out.println("Average value: ");
        average(inputTable);
        System.out.println("Prime numbers: ");
        isPrime(inputTable);


    }
}

Second code

public class Complex {
// datové složky

    public double re;
    public double im;
// konstruktory

    public Complex() {
    }

    public Complex(double r) {
        this(r, 0.0);
    }

    public Complex(double r, double i) {
        re = r;
        im = i;
    }


    public double abs() {
        return Math.sqrt(re * re + im * im);
    }

    public Complex plus(Complex c) {
        return new Complex(re + c.re, im + c.im);
    }

    public Complex minus(Complex c) {
        return new Complex(re - c.re, im - c.im);
    }


    public String toString() {
        return "[" + re + ", " + im + "]";
    }
}


Let's start with a simple example:

public class Main
{
    public static void main(final String[] argv)
    {
        final Person personA;
        final Person personB;

        personA = new Person("John", "Doe");
        personB = new Person("Jane", "Doe");

        System.out.println(personA.getFullName());
        System.out.println(personB.getFullName());
    }
}

class Person
{
    private final String firstName;
    private final String lastName;

    public Person(final String fName,
                  final String lName)
    {
        firstName = fName;
        lastName  = lName;
    }

    public String getFullName()
    {
        return (lastName + ", " + firstName);
    }
}

I am going to make a minor change to the getFullName method now:

public String getFullName()
{
    return (this.lastName + ", " + this.firstName);
}

Notice the "this." that I now use.

The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):

public class Main
{
    public static void main(final String[] argv)
    {
        final Person personA;
        final Person personB;

        personA = new Person("John", "Doe");
        personB = new Person("Jane", "Doe");

        System.out.println(Person.getFullName(personA));
        System.out.println(Person.getFullName(personB));
    }
}

class Person
{
    private final String firstName;
    private final String lastName;

    public Person(final String fName,
                  final String lName)
    {
        firstName = fName;
        lastName  = lName;
    }

    public static String getFullName(final Person thisx)
    {
        return (thisx.lastName + ", " + thisx.firstName);
    }
}

So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.

Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.


First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:

Car
properties - engine, gearbox, chasis
methods - ignite, run, brake

The ignite method depends on the engine field.

Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations. Take a look at java.lang.Math - it's methods are static for that precise reason.


The program below has been coded by making the methods non-static.

import java.util.Scanner;

public class NumberArray2{

   private int tab[]; // Now table becomes an instance variable.

   // allocation and initilization of the table now happens in the constructor.
   public NumberArray2() {
      Scanner Scan = new Scanner(System.in);
      System.out.println("How many numbers?");
      int s = Scan.nextInt();
      tab = new int[s];

      System.out.println("Write a numbers: ");
      for(int i=0; i<tab.length; i++){
         tab[i] = Scan.nextInt();
      }
      System.out.println("");
   }

   public void output(){
      for(int i=0; i<tab.length; i++){
         if(tab[i] != 0)
            System.out.println(tab[i]);
      }
   }

   public void max(){
      int maxNum = 0;
      for(int i=0; i<tab.length; i++){
         if(tab[i] > maxNum)
            maxNum = tab[i];
      }
      System.out.println(maxNum);
   }

   public void divide(){
      for(int i=0; i<tab.length; i++){
         if((tab[i] % 3 == 0) && tab[i] != 0)
            System.out.println(tab[i]);
      }
   }

   public void average(){
      int sum = 0;
      for(int i=0; i<tab.length; i++)
         sum = sum + tab[i];
      int avervalue = sum/tab.length;
      System.out.println(avervalue);
   }

   public void isPrime() {
      for (int i = 0; i < tab.length; i++) {
         if (isPrimeNum(tab[i])) {
            System.out.println(tab[i]);
         }
      }
   }

   public boolean isPrimeNum(int n) {
      boolean prime = true;
      for (long i = 3; i <= Math.sqrt(n); i += 2) {
         if (n % i == 0) {
            prime = false;
            break;
         }
      }
      if ((n % 2 != 0 && prime && n > 2) || n == 2) {
         return true;
      } else {
         return false;
      }
   }

   public static void main(String[] args) {

      // instatiate the class.
      NumberArray2 obj = new NumberArray2();

      System.out.println("Written numbers:");
      obj.output(); // call the methods on the object..no need to pass table anymore.
      System.out.println("Largest number: ");
      obj.max();
      System.out.println("All numbers that can be divided by three: ");
      obj.divide();
      System.out.println("Average value: ");
      obj.average();
      System.out.println("Prime numbers: ");
      obj.isPrime();
   }
}

Changes made:

  • int tab[] has now been made an instance variable.
  • allocation and initialization of the table happens in the constructor. Since this must happen for every instantiated object, it is better to keep this in a constructor.
  • The methods need not be called with table as an argument as all methods have full access to the instance variable(table in this case)
  • The methods have now been made non-static, so they cannot be called using the class name, instead we need to instantiate the class to create an object and then call the methods on that object using the obj.method() syntax.


It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)

Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {

In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.

Before:
NumberArray2.isPrimeNum(11);

After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class numberarray2.isPrimeNum(11); // Call a method of the given object

In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object). When you deside to not include a constructor the java compilator will add on for you. It would look like this: public NumberArray2(){};

Hope this helps. And you are right, this looks like homework :D

I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).

The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.


I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.

Person john = new Person("John",18);
Person alice = new Person("Alice",17);

if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"

static is used when you want to retain a value of something across all objects of the same class.

class Person{
static int amountOfPeopleCreated;
   public Person(string name, int age){
      amountOfPeopleCreated++;
      setName(name);
      setAge(age);
   }
   ...
}

so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜