Mark Enlightenment
Mark Enlightenment

Reputation: 33

Java OOP; creating several objects

I am trying to store students' data in main class, in the student class I did the following:

public class Student {
        public static String name = "UNKNOWN";
        Student(){

        }

        Student(String name) {
            this.name = name;}

While in main I did the following:

public class Main {

    public static void main (String[] args) {
        //s1 is short for student1
        Student s1 = new Student ("Chris");
        Student s2 = new Student ("Layla");
        Student s3 = new Student ("Mark");

This issue is, whenever I print a sx.name I'd always print the last one. So for the following code:

System.out.println(s1.name);

I'd get Mark, while it should be Chris.

Upvotes: 0

Views: 91

Answers (2)

lisz1012
lisz1012

Reputation: 21

The static variable name is accessed by instances, which is not recommended in Java. You can make it non-static. The IDE, such as IDEA, will give you some hint/warning about this issue, like: enter image description here

So with the help of IDEs, you can easily find some potential issues.

Upvotes: 0

Yati Sawhney
Yati Sawhney

Reputation: 1402

Yes, Because static fields are shared by all the objects. Please change your code as follows:

public class Student {
        public String name;
        Student(){

        }

        Student(String name) {
            this.name = name;

}

public static void main (String[] args) {
        //s1 is short for student1
        Student s1 = new Student ("Chris");
        Student s2 = new Student ("Layla");
        Student s3 = new Student ("Mark");
}

When to use static in java?

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Upvotes: 2

Related Questions