Lucious Jackson
Lucious Jackson

Reputation: 1

Why is the 'Public' keyword not being recognized"?

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();

Upvotes: 0

Views: 778

Answers (2)

Noor A Shuvo
Noor A Shuvo

Reputation: 2807

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 anonymous window. There is no problem with that.

enter image description here

Upvotes: 0

Alp
Alp

Reputation: 21

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();

Upvotes: 1

Related Questions