C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

How can we Create Objects for a Class?

0 votes
76 views
asked by augustaina Sr Member (4,820 points)

2 Answers

0 votes
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();    
  }
}
 
 
answered by smith Geek (15,340 points)
0 votes
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;
    }
}
answered by augustaina Sr Member (4,820 points)

Related questions

0 votes
1 answer 106 views
0 votes
1 answer 15 views
15 views asked by sara Guru (24,570 points)
0 votes
1 answer 41 views
41 views asked by rock Expert (14,990 points)
0 votes
1 answer 93 views
0 votes
1 answer 34 views
34 views asked by sara Guru (24,570 points)
...