I am currently studying Java for my procedural programming module. I've read that in procedural programming, records must be defined outside the main class but that the accessor methods for these records must be defined within the main class.
An example is shown below:
class person // Record definition
{
String name;
int age;
}
class personalDetails // Main class
{
public static void main (String [] a)
{
mainMethod();
System.exit(0);
}
public static void mainMethod()
{
// Main method
}
// Getter method to get name
public static String getName(person p)
{
return p.name;
}
// Getter method to get age
public static int getAge(person p)
{
return p.age;
}
// Setter method to set name
public static void setName(person p, String name)
{
p.name = name;
}
// Setter method to set age
public static void setAge(person p, int age)
{
p.age = age;
}
}
Why is this necessary?
I know that we cannot define the accessor methods within the definition of the record as this is an OOP approach but I don't fully understand why can't we define the record within the main class where the accessor methods are.
In "traditional" procedural programming code and the data it operates on are quite separate: You have data structures that don't have any code assigned to it and you have code that doesn't have the ability to store code.
In Java the two are co-mingled: all code and all data has some relation to classes (I'm including interfaces, enums and records in this definition as well, the distinction is not important for this): methods are part of a class and fields belong to classes as well.
So in the normal Java style you'd define the fields of a type together with methods that act on it:
Here you clearly combine both the data (the fields
nameandage) and the code (the methodgetDescription) into a single unit.In procedural programming those two things would be separate (I'm using a Java-style syntax here, but that exact code I show is not valid Java).
Methods that are not in any type are not possible in Java, so to get close to this, you'll have to put it into a class (any class really):
Note also that I made the method
staticindicating that it doesn't act on an instance ofPersonMethods. This is another indication that we're using Java to implement a programming model that it's not meant to implement.Where exactly those methods are doesn't really matter. In theory you could even put them in
Personitself and keep themstaticwith aPerson pparameter, but that would probably look too much like regular OOP.