Developer community
0 votes
80 views
asked by Sr Member (4.8k points) 10 23 31 | 80 views

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 Geek (15.3k points) 15 40 60
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 Sr Member (4.8k points) 10 23 31

Related questions

0 votes
1 answer
asked by smith Geek (15.3k points) 15 40 60 | 115 views
0 votes
1 answer
asked by sara Guru (24.6k points) 29 51 77 | 17 views
0 votes
1 answer
asked by rock Expert (15k points) 15 23 29 | 45 views
0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 23 31 | 97 views
0 votes
1 answer
asked by sara Guru (24.6k points) 29 51 77 | 38 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


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

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users