Book Image

Introduction to Programming

By : Nick Samoylov
Book Image

Introduction to Programming

By: Nick Samoylov

Overview of this book

Have you ever thought about making your computer do what you want it to do? Do you want to learn to program, but just don't know where to start? Instead of guiding you in the right direction, have other learning resources got you confused with over-explanations? Don't worry. Look no further. Introduction to Programming is here to help. Written by an industry expert who understands the challenges faced by those from a non-programming background, this book takes a gentle, hand-holding approach to introducing you to the world of programming. Beginning with an introduction to what programming is, you'll go on to learn about languages, their syntax, and development environments. With plenty of examples for you to code alongside reading, the book's practical approach will help you to grasp everything it has to offer. More importantly, you'll understand several aspects of application development. As a result, you'll have your very own application running by the end of the book. To help you comprehensively understand Java programming, there are exercises at the end of each chapter to keep things interesting and encourage you to add your own personal touch to the code and, ultimately, your application.
Table of Contents (21 chapters)

Exercise – Restricting a class instantiation to a single shared instance

Write a class in such a way that it guarantees that only one object can be created.

Answer

Here is one possible solution:

public class SingletonClassExample {
private static SingletonClassExample OBJECT = null;

private SingletonClassExample(){}

public final SingletonClassExample getInstance() {
if(OBJECT == null){
OBJECT = new SingletonClassExample();
}
return OBJECT;
}

//... other class functionality
}

Another solution could be to make the class private inside the factory class and store it in the factory field, similarly to the previous code.

Be aware, though, that if such a single object has a state that is changing, one has...