In: Computer Science
Class Exercise: Constructor using JAVA
Let’s define a Class together and have a constructor while at it.
- What should the Class object represent? (What is the “real life object” to represent)?
- What properties should it have? (let’s hold off on the methods/actions for now – unless necessary for the constructor)
- What should happen when a new instance of the Class is created?
- Question: What are you allowed to do in the constructor?
- Let’s test this out (demo).
The Class in any Object Oriented Programming Language represents a template or a blue print.
So an object of that class is an instance of a class.
Class has just logical existence but an object has physical existence.
When an object is created, the space required for the object is allocated. Any constructors that class has are executed on the object. The constructor should have the same name as the class.
We can initialise the variables, allocate memory.
Please find below the demo program.
import java.util.*;
import java.lang.*;
import java.io.*;
class sample
{
int demo;
sample()
{
demo=100; //the
variable is initialised using the constructor.
}
void display()
{
System.out.println("Demo value is
"+demo);
}
}
class Demo_class
{
public static void main (String[] args) throws
java.lang.Exception
{
sample s=new
sample(); //a new object is created.
s.display();
}
}