0

I am new to Salesforce Development/Apex and am running practice exercises. When I run this code thru the 'Anonymous Apex' window, it throws an error reading: "Unexpected token 'Public'. " Please help me understand what my problem is.

I have created the following Employee Object that should print:

//Name: Lucious; Designation:CEO //Name: Johanna Designation: COO

Here is my Code:

public class Employee
{
    public String name;
    public designation;
    public void show()
{
    System.debug('Name: ' + name);
    System.debug('Designation: ' + designation);
}

}

Employee e1 = new Employee();
Employee e2 = new Employee();

   e1.name = 'Lucious';
   e1.designation = 'CEO';

   e2.name = 'Johanna';
   e2.designation = 'COO';

e1.show();
e2.show();

2 Answers2

1

You cannot define a class directly inside the Anonymous Apex window in Salesforce. The Anonymous Apex window is designed to execute standalone statements or expressions, such as variable assignments, method calls, or queries. It does not support defining classes, interfaces, or other Apex types.

Once you have created the Apex class file, you can save it and then use it in the Anonymous Apex window to instantiate objects of that class, call methods, or perform other operations using the defined class.

Create an Apex class called Employee

public class Employee
{
    public String name;
    public String designation;
    public void show()
    {
        System.debug('Name: ' + name);
        System.debug('Designation: ' + designation);
    }
}

Then, when you go to the Anonymous window initiate the variables and call your methods from that class:

Employee e1 = new Employee();
Employee e2 = new Employee();

e1.name = 'Lucious';
e1.designation = 'CEO';

e2.name = 'Johanna';
e2.designation = 'COO';

e1.show();
e2.show();
Alp
  • 21
  • 3
  • Thank you very much, Alp! I typed my code out here to show it in its entirety but, I did in fact execute the code in the way you suggest. It still won't recognize that "Public" keyword and throws and error. I also have Salesforce-CLI and Apex installed on my VS Code Editor and when I run the very same code on there it throws the very same error. I am truly baffled. – Lucious Jackson Jun 03 '23 at 08:00
  • Okay, Y'all. I am gonna sound like a total lop but, my code wasn't running because I wasn't saving the Object in the Console before trying to execute the Apex Anonymous Window. My Bad. – Lucious Jackson Jun 03 '23 at 14:13
0

The only issue is with this line public designation;

Just, change the line to public String designation;

It will work!

Note: You can define a class in Annonymous Window. There is no problem with that.

enter image description here

Noor A Shuvo
  • 2,639
  • 3
  • 23
  • 48