Click here to Skip to main content
15,885,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all i am not here today to ask if my code works right . I am here to ask if i am doing it right and if i am following the proper java coding rules . Iv been in other sites and places where they have mentioned that i am bad at this and bad at that which i already know i want to get better.With that being said i will move on to the question.

I think i know my basic java(by basic java i mean how to do a simple coding but not to say why we used this instead of doing it like this)

So if am to start where and why do we make variables static ? now i know that it is for the encapsulation . What if i have 2 classes and i am initializing something inside one class and then i want to access that value i assigned to it inside another class ? or inside another method ? do i make them static ? or instance. What if i want to use some variables i have assigned in one class in another can i use setters and getters ? here is something i have done , I know that there are issues with the coding as i have gone and googled about everything i should and shouldnt do . I just need confirmation
Java
class Character{


    private static int name=null;
    private static age=0;
    private static String class_name=null;
    private static double hitPoints = 0;
    private static int[] stats = {1,2,3,4,5,6}
    
   
    public static int[] getStats() {
        return stats;
    }


    public static String getClass_name() {
        return character_class;
    }



    public static double getHitPoints() {
        return hitPoints;

      }
     public void getvalues() {

       
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter  Name:");
             name= sc.next();
            System.out.print("Enter Your age:");
            age = sc.nextInt();
            System.out.println("Enter your hitpoints");
            hitpoints=sc.nextInt();

class Main{


         public void display(){

         System.out.println("Your name is :"+name);
         System.out.println("Your age is  :"+age);
         System.out.print("Your hitpoints :"+hitpoints);

         for(int i=0;;i<6;i++){
         System.out.print("Your array is :"+stats[i]);
         }
}
public static void main(String args[]){

   Character c1=new Character();
   c1.getvalues();
   display();


}

}


Here i am trying to get some values in one class, and then print it using another class. I am using getvalues to get the user inputs and then use display() to print it out.Obviously this is not my project and mine is to create a game. Which is alot bigger but basically can say its the same concept . Either way what i want to know is the use of static and the getters . Am i doing it right, white needs to be changed within the concept(Please note that this code is not checked if it is working or not since that is not what i am looking for i just want to know f the concept is write as in the coding patterns and segments. Ignore if anything is wrong or if it doesnt compile.

Thank you all for taking your time.

What I have tried:

I have done my reading but i am not sure what to use static and setters and getters and where to use them just need help with and is it ok to use them to connect between classes when it comes to variable values
Posted
Updated 10-Apr-18 5:43am
v2

As a first explanation of static and "non-"static.
A static class does not need an instance and will be created without you needing to instanciate it by "MyClass class = new MyClass()".
Think of it as a configuration or probably a game engine where it would simply not make sense to create instances of it. It's basically a design decision.
So static things are always available

A "regular" class always needs an instance before you can use it. This means that you can create multiple instances of it. As an example you could "improve" your Character by having multiple stats objects ("class Stats") and each hold different values of the same type instead of using an array.

To make it more clear, think of car class having tyres, each tyre on the car is one instance of the class tyre.
So non-static stuff needs to be instantiated and initialized.

And you should not make getters/setters static, you want to get the values of your current instance and therefore it would not make sense to make them static.

If you have any further questions feel free to ask, hope i helped you a bit.
 
Share this answer
 
Comments
Member 13771743 10-Apr-18 12:22pm    
@jocen i am aware of the usage of double points2=character.getHitpoints();
what i am asking is in the above one lets say i am prompting the user to enter 10 values for "10 different skills" so here i can use a for-loop or i can use 10 variables or i can store all of these inputs in an array. Lets say i did this in the character class as i have mentioned above. What if i want to use them inside another class ? is it correct for me to define those 10 variables (assuming i am using 10 variables instead of an array and what not) static so i can access them inside the other class ? Or assume i am using the array to store them is it correct for me to define the array out side an method(basically right after defining the class exactly like v done in the example) so i can use it inside another class ? if not how should i go about doing so ? is setters and gettes an option ? lets say i wanted to get this array values printed but those are inside a method in another class? is it correct for me to define them like iv done ? if not please explain how i should do so by using the example i have provided.
private static int [] arr={1,2,3}

Thnk you
HobbyProggy 11-Apr-18 1:41am    
Or you could use a stats class and make an array or list of it, adding each value by the user. You then just need getters and setters to set or retrieve the values from your stats. If not totally necessary avoid static!
When a class has static members, all instances of the class will use the same member. The member exists only at one place in memory. With non-static members, each instance has its own copy stored at different memory locations.

When - or if it all - to use static members depends on what you want to do. If you are not sure avoid them. An example for using static members might be a class that uses one time initialisation for values that do not change during runtime like the screen resolution:
Java
class SomeClass {
    private static boolean initialised;
    private static int width;
    private static int height;
    
    public SomeClass() {
        // Called the first time
        if (!initialised)
        {
            width = getScreenWidth();
            height = getScreenHeight();
            // Will never execute this block again
            initialised = true;
        }
    }
}

When having static member variables you should also make the getter and setter functions static. While not really necessary it allows using them without having a class instance:
Java
// Works always
Character c1 = new Character();
double points1 = c1.getHitPoints();
// Works only when getHitPoints() is static
double points2 = Character.getHitPoints();

For your case change the stats member to a single int and create multiple instances of the class:
C++
Character characters = new Character[6];
for (int i = 0; i < characters.length; i++) {
    // Now the user input will not overwrite the previous data anymore
    characters[i].getValues();
}
// The display() function has to be changed to display(Character[] characters)
//  and loop through the array items.
display(characters);
If some members are constant for all instances, you can make those static. But there are none in your example.
 
Share this answer
 
Comments
Member 13771743 10-Apr-18 10:49am    
@jocen i am aware of the usage of double points2=character.getHitpoints();
what i am asking is in the above one lets say i am prompting the user to enter 10 values for "10 different skills" so here i can use a for-loop or i can use 10 variables or i can store all of these inputs in an array. Lets say i did this in the character class as i have mentioned above. What if i want to use them inside another class ? is it correct for me to define those 10 variables (assuming i am using 10 variables instead of an array and what not) static so i can access them inside the other class ? Or assume i am using the array to store them is it correct for me to define the array out side an method(basically right after defining the class exactly like v done in the example) so i can use it inside another class ? if not how should i go about doing so ? is setters and gettes an option ? lets say i wanted to get this array values printed but those are inside a method in another class? is it correct for me to define them like iv done ? if not please explain how i should do so by using the example i have provided.
private static int [] arr={1,2,3}

Thnk you
Jochen Arndt 10-Apr-18 12:44pm    
If you need to store 10 different skills you can use an array as class member. If you need to access that from another class (or another instance of the same class) you have to use getter and setter functions using a pointer or reference to the class instance.

But don't make them static if it is not necessary.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900