The difference between Classes, Objects, and Instances - java

What is a class, an object and an instance in Java?

A class is a blueprint which you use to create objects. An object is an instance of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class.
This is easy to understand if you look at an example. For example, suppose you have a class House. Your own house is an object and is an instance of class House. Your sister's house is another object (another instance of class House).
// Class House describes what a house is
class House {
// ...
}
// You can use class House to create objects (instances of class House)
House myHouse = new House();
House sistersHouse = new House();
The class House describes the concept of what a house is, and there are specific, concrete houses which are objects and instances of class House.
Note: This is exactly the same in Java as in all object oriented programming languages.

Java (and any other programming language) is modeled in terms of types and values. At the theoretical level, a value is a representation for some quantum of information, and a type is a set of values. When we say value X is an instance of type Y, we are simply saying that X is a member of the set of values that is the type Y.
So that's what the term "instance" really means: it describes a relationship not a thing.
The type system of the Java programming language supports two kinds of types, primitive types and reference types. The reference types are further divided into the classes and array types. A Java object is an instance of a reference type.
An object is a class instance or an array. (JLS 4.3.1)
That's the type theoretic view.
In practice, most Java developers treat the words "instance" and "object" as synonyms. (And that includes me then I'm trying to explain something quickly.) And most developers use the word "value" rather than "instance" to refer to an instance of a primitive type.

A class is basically a definition, and contains the object's code. An object is an instance of a class
for example if you say
String word = new String();
the class is the String class, which describes the object (instance) word.
When a class is declared, no memory is allocated so class is just a template.
When the object of the class is declared, memory is allocated.

I like Jesper's explanation in layman terms
By improvising examples from Jesper's answer,
class House {
// blue print for House Objects
}
class Car {
// blue print for Instances of Class Car
}
House myHouse = new House();
Car myCar = new Car();
myHouse and myCar are objects
myHouse is an instance of House (relates Object-myHouse to its Class-House)
myCar is an instance of Car
in short
"myHouse is an instance of Class House" which is same as saying "myHouse is an Object of type House"

Class is Data Type,You use this type to create object.
Instance is Logical but object is Physical means occupies some memory.
We can create an instance for abstract class as well as for interface, but we cannot create an
object for those.
Object is instance of class and instance means representative of class i.e object.
Instance refers to Reference of an object.
Object is actually pointing to memory address of that instance.
You can’t pass instance over the layers but you can pass the object over the layers
You can’t store an instance but you can store an object
A single object can have more than one instance.
Instance will have the both class definition and the object definition where as in object it will have only the object definition.
Syntax of Object:
Classname var=new Classname();
But for instance creation it returns only a pointer refering to an object, syntax is :
Classname varname;

Class : Structure
Object : Physical Manifestation
Instance : each object created from class
Reference : Address of Object

In java, the objects are spawned on heap memory. These require reference to be pointed and used in our application. The reference has the memory location of the object with which we can use the objects in our application. A reference in short is nothing but a name of the variable which stores the address of the object instantiated on a memory location.
An instance is a general term for object. FYI, Object is a class.
For Example,
Class A{
}
A ref = new A();
For the above code snippet, ref is the reference for an object of class A generated on heap.

Honestly, I feel more comfortable with Alfred blog definitions:
Object: real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and behavior (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.
Class: is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.
Instance: An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.
Given the next example:
public class Person {
private int id;
private String name;
private int age;
public Person (int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
public static void main(String[] args) {
//case 1
Person p1 = new Person(1, "Carlos", 20);
Person p2 = new Person(1, "Carlos", 20);
//case 2
Person p3 = new Person(2, "John", 15);
Person p4 = new Person(3, "Mary", 17);
}
}
For case 1, there are two instances of the class Person, but both instances represent the same object.
For case 2, there are two instances of the class Person, but each instance represent a different object.
So class, object and instance are different things. Object and instance are not synonyms as is suggested in the answer selected as right answer.

If you have a program that models cars you have a class to represent cars,
so in Code you could say:
Car someCar = new Car();
someCar is now an instance of the class Car. If the program is used at a repairshop and the someCar represents your car in their system, then your car is the object.
So Car is a class that can represent any real world car
someCar is an instance of the Car class and
someCare represents one real life object (your car)
however instance and object is very often used interchangably when it comes to discussing coding

Any kind of data your computer stores and processes is in its most basic representation a row of bits. The way those bits are interpreted is done through data types. Data types can be primitive or complex. Primitive data types are - for instance - int or double. They have a specific length and a specific way of being interpreted. In the case of an integer, usually the first bit is used for the sign, the others are used for the value.
Complex data types can be combinations of primitive and other complex data types and are called "Class" in Java.
You can define the complex data type PeopleName consisting of two Strings called first and last name. Each String in Java is another complex data type. Strings in return are (probably) implemented using the primitive data type char for which Java knows how many bits they take to store and how to interpret them.
When you create an instance of a data type, you get an object and your computers reserves some memory for it and remembers its location and the name of that instance. An instance of PeopleName in memory will take up the space of the two String variables plus a bit more for bookkeeping. An integer takes up 32 bits in Java.
Complex data types can have methods assigned to them. Methods can perform actions on their arguments or on the instance of the data type you call this method from. If you have two instances of PeopleName called p1 and p2 and you call a method p1.getFirstName(), it usually returns the first name of the first person but not the second person's.

The concept behind classes and objects is to encapsulate logic into single programming unit. Classes are the blueprints of which objects are created.
Here an example of a class representing a Car:
public class Car {
int currentSpeed;
String name;
public void accelerate() {
}
public void park() {
}
public void printCurrentSpeed() {
}
}
You can create instances of the object Car like this:
Car audi = new Car();
Car toyota = new Car();
I have taken the example from this tutorial

Class
It has logical existence, i.e. no memory space is allocated when it is created.
It is a set of objects.
A class may be regarded as a blueprint to create objects.
It is created using class keyword
A class defines the methods and data members that will be possessed by Objects.
Object
It has physical existence, i.e. memory space is allocated when it is created.
It is an instance of a class.
An object is a unique entity which contains data members and member functions together in OOP language.
It is created using new keyword
An object specifies the implementations of the methods and the values that will be possessed by the data members in the class.

A class is a blueprint that is needed to make an object(= instance).
The difference between an object and an instance is, an object is a thing and an instance is a relation.
In other words, instance describes the relation of an object to the class that the object was made from.

The definition "Object is an instance of a class", is conceptually wrong, but correct as per implementation. Actually the object oriented features are taken from the real life, for focusing the mind of programmer from more to less. In real life classes are designed to manage the object.For eg- we human beings have a caste, religion,nationality and much more. These casts, religion, nationality are the classes and have no existence without human beings. But in implementation there is no existence of objects without classes.
Object- Object is an discrete entity having some well defined attribute. Here discrete mean something that makes it unique from other. Well defined attribute make sense in some context.
Class- Classification of object having some common behaviour or objects of some common type.

While the above answers are correct, another way of thinking about Classes and Objects would be to use real world examples: A class named Animal might contain objects like Cat, Dog or Fish. An object with a title of Bible would be of class Book, etc. Classes are general, objects are specific. This thought example helped me when I was learning Java.

Class is a template or type. An object is an instance of the class.
For example:
public class Tweet {
}
Tweet newTweet = new Tweet();
Tweet is a class and newTweet is an object of the class.

Related

How does class object relation work?

What happens when we create an instance of a class? I mean, will every field and method of that class be inside that object (with allocated memory) or will it not have anything inside and have a reference to its class, instead. (First option looks like a waste of memory.)
Whenever a new object is created, new memory is allocated in the heap space (dynamic memory). This space is reserved for everything that's specific to this single instance of a class. That means every field (instance field, not the static one) would have its own separate location in memory.
For methods, things are different since they are common for all instances of a class, which means you would have one method in memory which would be referred to by each instance of a class.
If you wonder where are local variables of a method stored: they are stored on the stack, meaning they are not shared between invocations of that method.
Also, methods are stored in the 'code memory', separate from instance fields.
The full concept of OOP (Object Oriented Programming) is being able to abstract the reality by "describing" the objects.
To accomplish this purpose we're able to declare an object attributes, for example.
You can have an object Person, this person has different attributes, such as name, age, address. Also you can describe the different actions of this person, such as eating, taking a bath, etc. The abstraction of this would look like:
class Person(){
int age;
String name;
String address;
void eating(){
//describe the process of eating
}
void takeBath(){
//describe the process of taking a bath
}
}
The whole purpose of this is that afterwards you can instantiate an Object Person and it will have all of it's attributes.
You can call the object in another class and instantiate it, this call will look like:
Person person1 = new Person(); //here you are saying that you have a new variable of type person
person1.name = "Eduardo"; //You're saying that his name is Eduardo
person1.age= 28; //he is 28 years old
person1.eating(); //he's eating, I like to eat tho.
Person person2 = new Person(); //You are saying that there's another person
person2.name = "Maria"; //her name is Maria
person2.age = 31; //She's 31 years old
person2.takeBath(); She's taking a bath
As you can see I didn't have to declare again the methods or attributes of the class, simply created a new object and started setting the attributes (please be aware of the difference between declaring and setting, to declare is to say there is an attribute of X type; setting is giving a value to that attribute).
There's another very useful property in OOP called heritage. Lets say we want to describe a Programmer; a programmer is a Person and he can do whatever a person does but also he codes and has a preferred language this would look like:
class Programmer extends Person { // I'm declaring the class but also I'm saying it's a person, so it will have all the attributes and methods of the Person class.
String preferredLanguage; //I will only declare the new attribute that is preferred Language, name, age and address are set because it's a person
void code(){
//the process of making very awesome things
}
}
And then I can instantiate another object Programmer
Programmer person3 = new Programmer(); //I called it person3 so you can understand it's only a variable, you can call it as you wish.
person3.name = "Berkay"; //Set the name without the need of declaring it in the method programmer, it's been inherit by the class Person
person3.code();//it can code!
person3.takeBath(); //A method of Person
person3.code(); //method of Programmer
At this stage I'd like to point that Programmer having the attributes of Person doesn't mean the same way around. For example, trying to make this would be a mistake:
person1.code(); //person1 is a Person and it doesn't have the code method.
PS: There are a lot of things to improve in these code, it's far from using best practices. All I intend to do is to give a clear example of the way OOP works. I didn't test the code, it's only illustrative, it may contain typos

Objects Within Objects in Java

I've been given a coursework assignment where I have to build a prototype hotel booking system, in accordance with the specification, which is as follows:
You will need at least three classes:
Hotel
This should store all the essential information about a hotel,
including a name and some rooms.
Room
This should store the number of beds in a room.
Bed
This should store the size of a bed (i.e. single or double).
I'm totally confused about where to start!
I was under the impression that objects could not be contained within other objects.
For example, let's assume we instantiate a "Hotel" object. How would we then instantiate "Room" objects, and within that object, "Bed" objects?
How are these objects being stored? How do we interact with them indirectly, from another object?
Typically you don't need to nest classes into other classes, which are called inner classes, unless the work that a class takes care of can be chunked into small units that never need to be known outside it's parent class.
It sounds like the concept you want to look into is Composition. It's when an object holds a reference to another object.
public class Room {
private boolean isVacant;
public Room() {
isVacant = true; // The room starts vacant
}
// Pretend there is a way for clients to check in and out of the room
public boolean isVacant() {
return isVacant;
}
}
public class Hotel {
// Using composition, I can make an instance of one class
// available to the methods of another
private Room room101;
public Hotel(Room room101) {
this.room101 = room101;
}
public boolean isRoom101Vacant() {
return room101.isVacant();
}
}
Our hotel may not be very useful having only one room, but this example shows how you can "compose" one object into another. Methods of Hotel can now use methods of it's Room instance known as room101. You will want to think about how your rooms are structured, and how you want to represent it within your Hotel class. A few objects used to store collections of other objects include ArrayList and HashMap.
Edit:
this is a fairly difficult concept to understand before you understand what a class is compared to an instance of that class (an object). In the constructor of my sample Hotel class, I have a variable of type Room called room101. And outside of the constructor is an instance field of the same type and name.
Java will always refer to a variable or reference of the nearest scope. So if I have a method reference called room101, how can I refer to that other one declared outside the constructor, at instance level? That's where this comes in.
public class ThisExample {
// This is a separate variable at the instance level
// Lets call this global in the comments
private int a;
public ThisExample() {
// This is a separate variable in the method level,
// lets call this local in the comments
int a;
a = 5; // our local is now assigned 5
this.a = 10; // Our global is now assigned 10
this.a = a; // our global is now assigned to 5
a = this.a * 2; // our local is now assigned to 10
}
}
In short, this refers to "this" instance of a class. It's a way for an instance of a class to refer to itself as if from the outside. Just like how another object would refer to room101's method as room101.isVacant(). A method in the Room class would similarly do this.isVacant() for the same effect.
And as a final note, if there is only one declaration of a symbol within a class. The this keyword is implied. So Room can call it's own method just as well without it as long as there is no other conflicting symbols of the same name. (This doesn't occur with methods as much as with instance fields/local variables)
Hopefully this helps clear things up a bit!
Your assignment is how to model some real world concepts into code.
It appears that the core of your problem can be stated as a Guest can book a Room.
I don't want to do your work for you, so let me start by asking how you would write that in code? After that, we can address the "Hotel" and "Bed". Is this a major assignment or just a quick question? Your implementation would depend on this.
A rule to learn and apply is:
An action on an object in the real world, becomes a method of that object in an Object Oriented approach.

Why can a super class be initialized as a child class in Java?

In a nutshell, how and why is this possible:
Object obj=new MyClass();
Object is the superclass of all objects, therefore MyClass is a child class of Object. In general, in Java, Why is it possible to use the constructor of a child class in the parent class?
I understand how it could go the other way around, since the child has all the variables/methods of the parent class, so when you initialize them you are just initializing the variables specified in the parent constructor, that exist by definition in the child. The problem is, when you go the other way around, it is not necessarily true. A child can have variables the parent doesn't, so how is it possible to use the child constructor with the parent, when the parent does not even have the variables in the first place?
What uses does this feature have in development? I would think that if you want an instance of class B, you would declare it as B thing=new B(), and not A thing=new B(). This is probably my inexperience talking, so I would appreciate enlightenment on why and how a parent class can be initialized as one of its children.
Why is it possible to use the constructor of a child class in the
parent class?
This is not correct. When you do
Object obj = new MyClass();
Object obj; declares a reference of the type Object
and new MyClass(); returns a reference to the object it created.
So, you are instantiating a MyClass and assigning the reference to the object created to a reference of the type Object, and this is possible because MyClass is an Object.
As you say,
A child can have variables the parent doesn't
That's called extending the parent functionality (inheritance).
For your second question think about the classic Animal example: Suppose you create a Animal class and you create a method makeSound() on it.
Now you create two subclasses of Animal, Dog and Cat, that overrides the makeSound()method of Animal (a Dog barks and a Cat meows).
Imagine that you represent a room full of Animals (Dogs and Cats) using a List, and you want to make all of them makeSound(). Your list will be declared as List<Animal> because you don't know the kind of Animals that you will store.
And then you iterate over the List to call makeSound() for each Animal. It doesn't matter if the Animal is a Dogor a Cat, it will make it's sound.
And then imagine you want to add Birds to the List. Easy, isn't it?
You are thinking in terms of C++ semantics, but this is Java. In Java, all non-primitive type variables are references, not instances.
In C++, when you say
Object obj;
you allocate a new Object instance on stack or in static memory.
When you say
Object obj = new MyObject;
you invoke a constructor of Object class that takes MyObject pointer (or may be something else that MyObject can be converted to).
In Java,
Object obj;
does not create any instances of Object. It simply creates a variable that can have a reference to an Object instance, but at the moment does not refer to any. It is initialized to null.
Object obj = new MyObject();
allocates an instance of MyObject. It does not allocate a new instance of Object. It simply sets the variable to refer to the new instance. In C++ terms this is much more similar to
Object *obj = new MyObject();
So we're not constructing a parent instance from child instance. We're changing a value the variable is set to, from null to a new child instance.
First, you must get a clear understanding of things. Your example expression:
Object obj = new MyClass(); is actually a compound of two elementary operations.
The first one is creating an instance of MyClass: new MyClass(). The new keyword is basically the only way of actually obtaining an instance of a class (lets ignore runtime reflection to keep this simple), and you are literally naming what you want to create (MyClass) here by its constructor. There is no way to create anything other than what you literally named with the new keyword. The result of new is (implicitly) an instance of MyClass, but the explicit result of a new X is a reference of type X (the reference referring to the newly created instance).
Now the second operation is assigning the reference to your (new) MyObject to another reference of type Object. And this is valid because MyObject is an Object (due to inheritance).
Why would you need this?
This is an essential feature to actually make use of polymorphism. The ability to refer to any child class as its superclass is what makes polymorphism so powerful. You basically will use it everywhere where there is an aspect common to two classes, but there are also differences.
A real world example would be graphical user interfaces. There are buttons, lists, tables and panels in a window, which are all user interface elements, but each does a different thing. To present them neatly organized in a window, these elements are often nested into panels, more abstractly said into containers. Now a container doesn't care what kind of elements go into it, as long as they are components. But to handle them properly a container does need some basic information about these components, mostly how much space they occupy and how to actually draw them. So this is modelled as something like:
public abstract class Component {
public int getWidth() { ... }
public int getHeight() { ... }
public void paint(Graphics g) { ... }
}
public class Container extends Component {
public void add(Component child) { ... }
public void paint(Graphics g) {
for (Component child : children) {
child.paint(g);
}
}
}
Thats almost straight lifted out of the JDK, the point is, if you needed to refer to each Component as its concrete type, it would be impractical to build a Container, it would need extra code for each Component you decide to make (e.g. there would be an addButton, addTable and so on). So instead, Container just works with reference to Component. No matter what Component is created (e.g. Button, CheckBox, RadioButton etc.), since Container just relies on them to all be Component's, it can handle them.
Every class in Java is descended from Object. So MyClass is an Object, by definition, but a more specialized version of it. Think of it like this: every living creature is an Animal. A Cat is a special kind of animal; a specific type. Since the Cat is an Animal, you can still just call it an Animal:
Animal a = new Cat();
But doing so, with a, you can't do anything specific to a Cat, like meow() or purr(), but you can call methods which are valid for all Animals, such as breathe().
HTH
class myMobile{
public void call{
System.out.println("Mobile");
}
}
public class mainClass{
public static void main(){
Object o=new myMobile();
//here we can call methods which are common to all
// objects not specific to
// myMobile object
}
}
Because a MyClass is a Object. Note that java is special because Object is the superclass of every other class type (there is no equivalent in C++).
A more interesting example would be if you had a class or interface and one or more subclasses. This comes up all the time in OOD. Consider for example java's jdbc API: a common set of interfaces to connect and query a database that can be implemented by different concrete classes. You only need to code to the API and then at runtime use the implementation for your DB of choice.
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
i.e. every Java class is an Object. This is why.
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.
You have two separate things here:
The construction of a new instance
The assignment of that instance to
a variable
Since your instance of MyClass is also an instance of Object, this works well.
Consider the following, generic situation:
class A extends B implements C,D {
}
As your A is a B and also a C and a D and an Object, once you created an instance, you can (directly or indirectly) assign it to variables of all those types:
A a = new A();
B b = a;
C c = a;
D d = a;
Object o = a;
Your view on the fields or methods is limited by the type of the variable (i.E. as variable of type C, you only see the methods declared by C).
Nevertheless, your instance is always of the type you instanciated using the constructor, regardless of the variable type.

what is meaning of instance in programming?

I don't get it for long. Are there any alternative words similar to 'instance' that are easier to understand? For a non-programmer, how you explain instance? Instance is like example in normal person's world. I can't understand what it is if I don't even understand its meaning.
"instance" is best understood as it relates to "class" in programming. "Classes" are used to define the properties and behavior of a category of things. E.g. A "Car" class might dictate that all cars be defined by their make, model, year, and mileage.
But you can't provide specifics about a particular car (for example, that 1978 Chevy Impala with 205,000 miles on it that your uncle Mickey drives) until you create an "instance" of a Car. It's the instance that captures the detailed information about one particular Car.
To understand what an instance is, we must first understand what a class is.
A class is simply a modeling tool provided by a programming language for use in representing real world objects in a program or application.
The class is structured to accommodate an object's properties (member variables) and its operations (member functions/methods).
An Instance on the other hand is simply a variation of an object created from a class. You create an object variant (Instance) using a constructor which is a method within a class specifically defined for this purpose.
Consider a Car, if you wanted to represent it in your application you would define a class identified as Car which contains the properties of the car and the
operations that the car can perform.
It would look something close to this, supposing it was done in Java programming language:-
public class Car{
//the properties of the car
private String make;
private int year;
private int gear;
private int speed;
...
//constructor used to create instances of the car
public Car(String carMake, int yearManf){
year = yearManf;
make = carMake;
}
//Car Operation/methods
public void setGear(int gearValue){
gear = gearValue
}
public void applyBrake(int decrement){
speed -= decrement;
}
public void accelerate(int increment){
speed += increment;
}
...
}
Create an instance of a car:-
Car BMW = new Car("385 i", 2010);
BMW here is an instance of a car.
Going outside the world of programming for a second: you know what people are. You are an "instance" of the class "people" - I can talk about people in general (the class of objects), or if I have a specific one in mind, I talk of an "instance". An instance can have properties that are not automatically a consequence of being a member of the class. All humans have a heart, but not all humans have your name and date of birth.
I hope that clears it up a bit?
int main()
{
int a; //An instance of integer
int a,b; //two instances of integer
struct1 a; //An instance of struct1
return 0;
}
Here is a pretty standard definition:
An instance, in object-oriented programming (OOP), is a specific
realization of any object. An object may be varied in a number of
ways. Each realized variation of that object is an instance. The
creation of a realized instance is called instantiation.
Each time a program runs, it is an instance of that program. In
languages that create objects from classes, an object is an
instantiation of a class. That is, it is a member of a given class
that has specified values rather than variables. In a non-programming
context, you could think of "dog" as a class and your particular dog
as an instance of that class.
http://whatis.techtarget.com/definition/instance
Here is a good conversation about instances that may help you out: https://softwareengineering.stackexchange.com/questions/99202/is-it-called-class-or-object-instance
An object from an object or reference from an object.
Loosely speaking, there are patterns for making things and there are instances of those patterns.
A class is a pattern for creating objects. The objects that are created with it are instances of the class.
class C { };
C c; // instance of C
C d; // instance of C
A function template is a pattern for creating functions. The functions that are created with it are instances of the template. This is usually done implicitly, and referred to as "implicit instantiation".
template <class T> void f(T) { }
f(int); // implicit instantiation of f<int>
f(double); // implicit instantiation of f<double>
A class template is a pattern for creating classes. The classes that are created with it are instances of the template.
template <class T> class X { };
X<int> xi; // X<int> is instance of X, xi is instance of X<int>
X<double> xd; // X<double> is instance of X, xd is instance of X<double>
An instance is basically an object. In actual english, it can mean differently. In this case instance in english can mean 'To Refer' or 'Reference'. These objects instances in programming are also a reference to the source code.
with a simple example : we have a blueprint (class) represents student (object) with fields like name, age, course (class member). And we have 2 students here, Foo and Bob. So, Foo and Bob is 2 different instances of the class (Student class) that represent object (Student people).
credit: Alfred’s Computing Weblog
as far i have understood instance a pointer to object of class.
ps: i could be wrong.
Instance is a variable that holds the memory address of the Object.

what's the point of java constructor?

So I'm learning java. I'm one month in and I just learned about constructors. But I don't see the whole purpose of creating one. Why and when would I ever want to use one? I get the whole idea that it does not have a main method and you can call a constructor from your main class. Anyone can enlighten me on this topic, it would help me a great deal.
Constructors are what you use to initialize/set up the instances of your classes.
If you have an object that needs some processing before it is usable (initializing members for instance), you should do that in the constructor.
Ideally, you should never have "partially built" objects (i.e. objects that are "live", that you hold a reference to, but that are not yet usable). Without constructors, you'd be permanently creating partially built objects, and that is very error-prone. (Theory and practice don't always match, but keep that idea in mind.)
You use a constructor to create new objects. Yes, you can write Java just using static methods - but then you're really not writing object-oriented code, and you'll have a hard time using much of the standard library, either.
Most of your time you should be working with and thinking in terms of objects - and they need to be constructed before they can be used... and that's where constructors come in. They create an object, often with parameters specifying the initial state or other important information about the object.
To be honest, it's probably not worth worrying about them just yet, if you don't see the point yet. It's likely that as you learn more, you'll naturally start using objects more (maybe collections to start with, for example) and you'll get the hang of it. Rest assured, it is important to have constructors in Java, but I'm sure you'll understand why in the course of time. (Of course, if this answer has helped you to appreciate their value already, I'm glad - but if not, don't worry :)
It might seem as if you're having trouble understanding the basic concepts of objects and object-oriented programming. An explanation by example; This class represents a type of thing, namely a car:
public class Car{
// Licence plate number. This is private, so it can
// not be accessed directly from outside the class.
private String hiddenRegNr = "";
private static String description = "This is a car".
// The constructor, which sets the value of hiddenRegNr
public Car(String regNr){
hiddenRegNr = regNr;
}
// Method for reading hiddenRegNr, the only
// way to access it after instantiation.
public String getRegNr(){
return hiddenRegNr;
}
// A static method. Can be used withouth instantiation.
public static String getDesc(){
return description;
}
}
From some other class, you could call this class, and make instances of it; actual representations of different cars. They represent different cars, but are based on the same "model", i.e., the class Car.
Car myFirstCar = new Car("SR12345");
Car myOtherCar = new Car("XZ54321");
Now you have two different cars, with two different registration numbers. These are independent instances of the type car. They exist in memory, and may contain different values (in this case, different registration numbers).
myFirstCar.getRegNr(); // Will return SR12345
mySecondCar.getRegNr(); // will return xz54321
The first thing to notice here, is that you can only specify the registration number once per car, namely upon creation. That is the point of the constructor: It sets values, and does other stuff that needs to be done when objects (instances) are created.
Now, note the difference between getRegNr() and getDesc(): The keyword "Static" means that the second method is related directly to the class, and not to each instance. This means that:
Calls to getDesc() is made on the class, not an instance:
Car.getDesc();
Calls to getDesc() will return the same value for all instances of the class car
The variable description (which is also static) will be the same for all instances of Car
The static method getDesc() CAN NOT access the variable hiddenRegNr, since that variable is related to a specific instance. Trying to refer to a variable in an instance from a static context (such as getDesc()) will cause an exception to be thrown. You might say that hiddenRegNr will not have been set when you call
Car.getDesc();
because the constructor was never called, so it was never given any value.
Constructors are used to initialize a class and give parameters to a class. What is important is that they let you set the class state on creation. This allows you to use specific instances of a class with different data field values instead of relying on purely static information. Take the following example:
class Obj {
private int state = 0;
public Obj(int state) {
this.state = state;
}
public Obj() {
state = 1;
}
}
Now in main (or wherever) you can have:
Obj obj1 = new Obj();
Obj obj2 = new Obj(2);
The two objects have different states (one is at state 1, the other is at state 2). If you were relying on static methods and members, the objects would share one state and would not be independent of each other.
It is also important to note that constructors (specifically the new keyword) allocate memory for a given object internally so you don't have to worry about using malloc and other memory management. So they are important in that sense as well.
It is used to create objects. Objects are the main concept in OOP, so creating them is an important step. The main class method is just an entry point to your program. If you don't create objects your program will be procedural rather than object-oriented. This is why to use a constructor.
And why to create a constructor - sometimes you need to construct an object with some required parameters. There is also a default no-argument constructor, but if you want to initialize your object with additional arguments - you create a constructor taking those arguments.
Actually constructor is needed IF you need to assign unique initial state to an instance of a class. In Java i only just realized (by a friend) that we can do this:
public class MyClass1 {
private class MyClass2 {}
private MyClass2 myobj2 = new MyClass2();
}
So no need for implicit constructor.
But if something like follows, you need constructor.
public class MyClass1 {
private class MyClass2 {
private int id_ = 0;
public MyClass2(int id) { id_ = id; } // how to reach this?
}
private MyClass2 myobj2 = new MyClass2(1); // (this doesn't work. Not unique)
public MyClass1(int id) { myobj2 = new MyClass2(id); } // by this!
}
MyClass1 obj1 = new MyClass1(100);
MyClass1 obj2 = new MyClass1(200);
I will give you an example, imagine you have a car class.. when you call the constructor of the car class you have an car object. on this car object is possible to use diffent methods. And you could create as many as car objects as you want.

Categories