search
Login

Categories


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

3.8k questions

4k answers

117 comments

10.7k users

0 votes
83 views
asked Sr Member 4.8k points 10 25 31

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 Geek 15.3k points 16 41 63
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 Sr Member 4.8k points 10 25 31

Related questions

0 votes
1 answer 114 views
114 views
asked smith Geek 15.3k points 16 41 63
0 votes
1 answer 18 views
18 views
asked sara Guru 24.6k points 29 52 81
0 votes
1 answer 46 views
46 views
asked rock Expert 15k points 15 23 30
0 votes
1 answer 104 views
104 views
asked augustaina Sr Member 4.8k points 10 25 31
0 votes
1 answer 37 views
37 views
what is the use of class in java
asked sara Guru 24.6k points 29 52 81
...