Time for action – defining member access

Let's take a look at how to specify the access to our class member.

  1. Create a new file and save it as book.vala inside the src/ directory. Fill it with this:
    using GLib;
    
    public class Book : Object {
      private string title;
       private string isbn;
    
      public Book(string isbn, string title) {
        this.isbn = isbn;
        this.title = title;
      }
    
      public void printISBN() {
      stdout.printf("%s\n", isbn);
      }
    
      public void printTitle() {
        stdout.printf("%s\n", title);
      }
    }
  2. We need to add this to the project. Click on the Project menu and choose Add Source File....
  3. In the next dialog, click on the Target option, find hello_vala inside src/, and then, in the file selection box below it, choose book.vala.
  4. Modify the main function of hello_vala.vala to look like this:
    using GLib;
    
    public class Main : Object
    {
      public Main ()
      {
        var book = new Book("1234", "A new book");
        book.printISBN ();
      }
    
      static int main (string[] args)
      {
        stdout.printf ("Hello, world\n");  
        var main = new Main();
        return 0;
      }
    }
  5. Run it.
  6. Note that the program cannot be built.
    Time for action – defining member access

From the error message, we see that it rejects our access to call Book.printISBN (we read this dot notation as the printISBN member from the Book class).

This is what we have in the Main class constructor. There we instantiate Book into the book variable, and call printISBN there.

However, this is what we have in the Book class. It looks innocent, but it turns out that we missed something crucial that makes this function inaccessible from outside the class.

Here is a list of access specifiers that are recognized by Vala:

When we don't specify anything, the access is set to private by default. That is why our program cannot be built.

As mentioned previously, we don't put any specifiers in front of the printISBN function, so it is considered private. We can fix this by putting the correct access specifier in the printISBN function.

Q1. Which specifier from the following options do you think is correct?

Let's now move on, learning the basic data types available in Vala, meaning that we will take a look at how to interact with strings, numbers, and Boolean.