Let's take a look at how to specify the access to our class member.
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); } }
hello_vala
inside src/
, and then, in the file selection box below it, choose book.vala
.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; } }
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).
var book = new Book("1234", "A new book"); book.printISBN ();
This is what we have in the Main
class constructor. There we instantiate Book
into the book
variable, and call printISBN
there.
void printISBN() { stdout.printf(isbn); }
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?
public
, because we want to access it from Main
class which is outside the Book
class.printISBN
in the Main
constructor.