Field is a member of class that satisfies below
conditions.
a.
Mandatory name
b.
Mandatory access modifier like public,
protected, or private
c.
One or more optional modifiers like static,
final, synchronized
d.
An optional type
HelloWorld.groovy
class Employee { public static int noOfEmployees = 0 private String name private int id public Employee() { noOfEmployees++ } public String getName() { return name } public void setName(String name) { this.name = name } public int getId() { return id } public void setId(int id) { this.id = id } } Employee emp1 = new Employee() emp1.setName("Krishna") emp1.setId(123) println "id : ${emp1.getId()}, name : ${emp1.getName()}"
Output
id : 123, name : Krishna
Can I omit the type
to a field?
Yes, you can omit the type of a field, but it is
recommended to specify the type.
HelloWorld.groovy
class Employee { public static noOfEmployees = 0 private name private id public Employee() { noOfEmployees++ } public getName() { return name } public setName(name) { this.name = name } public getId() { return id } public setId(id) { this.id = id } } Employee emp1 = new Employee() emp1.setName("Krishna") emp1.setId(123) println "id : ${emp1.getId()}, name : ${emp1.getName()}"
Output
id : 123, name : Krishna
As you see above example, I omitted the type for fields
and methods (omitted return type and type to the arguments) also.
No comments:
Post a Comment