How can we Create Objects for a Class?
class Sphere {
double radius; // Radius of a sphere
Sphere() {
}
// Class constructor
Sphere(double theRadius) {
radius = theRadius; // Set the radius
}
}
public class MainClass {
public static void main(String[] arg){
Sphere sp = new Sphere();
}
}
Using the new keyword.
new is always followed by the constructor of the class.
For example, to create an Employee object, you write:
Employee employee = new Employee();
Here, ‘employee’ is an object reference of type Employee.
Once you have an object, you can call its methods and access its fields, by using the object reference.
You use a period (.) to call a method or a field.
For example:
objectReference.methodName
objectReference.fieldName
The following code, for instance, creates an Employee object and assigns values to its age and salary fields:
public class MainClass {
public static void main(String[] args) {
Employee employee = new Employee();
employee.age = 24;
employee.salary = 50000;
}
}
class Employee {
public int age;
public double salary;
public Employee() {
}
public Employee(int ageValue, double salaryValue) {
age = ageValue;
salary = salaryValue;
}
}