0

I've been learning Java for a bit now and over the last month I've gotten really stuck on something. I've gotten alot conflicting messages on how an object is made, like that there can only be one object per class - the constructor. But, I've also heard alot about how the new keyword is used to create objects in java. Could someone please clear up this confusion for me?

(thanks, and sorry if this seems like a dumb question.)

Madeline
  • 5
  • 4

3 Answers3

2

You've mixed a lot of concepts, here is how it goes (my version):

Class is something that describes the objects that will be created in JVM in runtime (one object, many objects - it depends on your actual program - what does it do).

Here is an example of Class definition:

public class Person {
   private String name;
   private int age;
}

Its important to understand that this alone is not really an object, only a definition of class, its like saying: "In my program persons that I'll want to create will look like this (read will have name and age)".

Now in order to create objects (real people/persons) you should use the word "new" in Java (other languages may do it in a different way). What is real person? Jack, John, Alice - they're all persons and might be created in your program.

Every Object should have a reference somewhere in the project so that you could be able to work with it:

Person john = new Person(...); // I'll explain about ... in a minute
Person jack = new Person(...);
Person alice = new Person(...);

So for now, we have 1 class definition (class Person) and we can create 3 objects (instances) of this class. So far so good.

Now how Java should know that instance john actually has the name "John" and he is, say, 40? In other words how exactly do you instantiate the data fields of the object during the object creation? The truth is that Java doesn't know but it allows You to define this by means of declaring constructors - a special way to instruct Java how to create an instance of the class, so we alter the class definition:

public class Person {
   private String name;
   private int age;

   public Person(String name, int age) {
      this.name = name;
      this.age  = age;
   }
} 

Now when we have a constructor, we create the objects (real persons, again) like this:

Person john = new Person("John", 40);
Person jack = new Person("Jack", 30);
Person alice = new Person("Alice", 32);

If we won't supply correct parameters to the constructor (the first one should be string, the second one is an integer), then the code won't compile at all.

So typically we have one class definition and we can create many objects out of it. Now its true is that in Java there are ways to define a class that in a way that won't allow the creation of more than one instance (this is called singleton) - but I think it will confuse you even more at this point, so for now if you haven't heard about these singletons - don't bother.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

In a very simple term I am giving my view just to understand object, but in depth you have to go and open java docs

class Employee{
int age       --->  attribute/variable/instancevariable/property/member of a class      
int salary   ---->  attribute/variable/instancevariable/property/member of a class
String name; ---->  attribute/variable/instancevariable/property/member of a class

//Constructor of a class as it's having same name as class name with no parameter 
Employee(){

}
//Constructor of a class as it's having same name as class name with three parameter 
Employee(String name,int age, int salary){
this.name=name;
this.age=age;
this.salary=salary;
}
//Constructor of a class as it's having same name as class name with one parameter 
Employee(String name){
this.name=name;
}
}

So when you do new Employee(); first jvm will look for new keyword and memory will be allocated based upon the number of attributes of class. Now you have memory with some allocated space(bytes) in it, you need to fill this memory(bytes) with some concrete value like (xyz,10,78)("charles",0,0) can be anything as you have only three attributes in class that's where constructor comes in place.

Constructor is used to initialize the object not to create the object

So through constructor if you don't supply any value then all you class level member(property) will be initialized to default value .

Employee e=new Employee();----> default value will be supply via jvm to the property of a class

Or if you want to supply any custom value for which we have defined another parameterized constructor in your class you can use

Employee charles=new Employee("charles",27,89);--> another new object with your customer value , jvm won't be supplying  any value and your object will be initialized with your own value .

So basically in layman term we can say new is used to create the object and constructor is used to supply initial value to it later on with help of method you can always change the value of your object.

One important point as many times you use new keyword that many times you will create the new object

to the question of your object is made per class, yes its true but that is the concept of singleton pattern at this point you need not to go in depth first clear all your oops and java concept then move to advance

Happy learning

henrycharles
  • 1,019
  • 6
  • 28
  • 66
0

First of all, class

A class is only a blueprint from which individual objects are created.

public class Student{  
        int id;  
        String name;  
    }

Describes the properties of the objects that are going to create using that class. "so in here a class is defined to have student name and id"

Object

You can say that an object is created from a class. The new keyword is used to create new objects. A class is a blueprint in which objects are created so an objects are the things i.e.instance that created from the class. You can create as many objects as you want, but it depends on heap size.

Constructor

Every class should have a constructor. If we do not write a constructor for our class, the Java compiler builds a default constructor for the class. The constructor will be invoked if a new object is created. It's a special type of method which is used to initialize the object.

public class Student{  
        // ---Parameterized Constructor of class Student ---
        public Student(int id, string name){
            this.id = id;
            this.name = name;
        } 
        // ------------      
        int id;  
        String name;   

    }

So again to objects, when an object is created,

Student sam = new Student(001, "Sam Winchester");

the new keyword will create a new object and invoke Student() constructor to initialize the object sam which is an instance of class Student(). I.e. pass the parameters to the constructor method. enter image description here

Output:

 /*    ID: 001
  *    Name: Sam Winchester
  */
Avishka Dambawinna
  • 1,180
  • 1
  • 13
  • 29