Book Image

Learning Java by Building Android Games - Second Edition

By : John Horton
Book Image

Learning Java by Building Android Games - Second Edition

By: John Horton

Overview of this book

Android is one of the most popular mobile operating systems presently. It uses the most popular programming language, Java, as the primary language for building apps of all types. However, this book is unlike other Android books in that it doesn’t assume that you already have Java proficiency. This new and expanded second edition of Learning Java by Building Android Games shows you how to start building Android games from scratch. The difficulty level will grow steadily as you explore key Java topics, such as variables, loops, methods, object oriented programming, and design patterns, including code and examples that are written for Java 9 and Android P. At each stage, you will put what you’ve learned into practice by developing a game. You will build games such as Minesweeper, Retro Pong, Bullet Hell, and Classic Snake and Scrolling Shooter games. In the later chapters, you will create a time-trial, open-world platform game. By the end of the book, you will not only have grasped Java and Android but will also have developed six cool games for the Android platform.
Table of Contents (30 chapters)
Learning Java by Building Android Games Second Edition
Contributors
Preface
Index

Scope: Methods and Variables


If you declare a variable in a method, whether that is one of the Android methods like onCreate or one of our own methods it can only be used within that method.

It is no use doing this in onCreate:

int a = 0;

And, then trying to do this in newGame or some other method:

a++;

We will get an error because a is only visible within the method it was declared. At first, this might seem like a problem but perhaps surprisingly, it is actually very useful.

That is why we declared those variables outside of all the methods just after the class declaration. Here they are again as a reminder.

public class SubHunter extends Activity {

    // These variables can be "seen"
    // throughout the SubHunter class
    int numberHorizontalPixels;
    int numberVerticalPixels;
    int blockSize;
    …
    …

When we do it as we did in the previous code the variables can be used throughout the code file. As this and other projects progress we will declare some variables outside of all methods...