Import Statements, Instance Members, and the Default Constructor

Similar documents
Basic Keywords Practice Session

Inheritance and Polymorphism in Java

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

ArrayList. Introduction. java.util.arraylist

The Java Main Method

Shallow Copy vs. Deep Copy

APCS Semester #1 Final Exam Practice Problems

The Object clone() Method

Chapter Two Bonus Lesson: JavaDoc

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

Software Design and Analysis for Engineers

Test-Driven Development (TDD)

PIC 10A Objects/Classes

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

CSE 142 Su 04 Computer Programming 1 - Java. Objects

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Checked and Unchecked Exceptions in Java

CS 177 Recitation. Week 1 Intro to Java

QUIZ. What is wrong with this code that uses default arguments?

1.00 Lecture 8. Using An Existing Class, cont.

Immutables. At first glance, you d think that immutables were useless, however, they provide many advantages.

CSC207 Week 3. Larry Zhang

Static Imports, Default Values, Number Types and More!

Write for your audience

QUIZ. How could we disable the automatic creation of copyconstructors

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Stage 11 Array Practice With. Zip Code Encoding

CPS122 Lecture: Defining a Class

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

The compiler is spewing error messages.

1: Introduction to Object (1)

Dealing with Bugs. Kenneth M. Anderson University of Colorado, Boulder CSCI 5828 Lecture 27 04/21/2009

Java Primer 1: Types, Classes and Operators

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

QUIZ. How could we disable the automatic creation of copyconstructors

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

Ch. 11: References & the Copy-Constructor. - continued -

After a lecture on cosmology and the structure of the solar system, William James was accosted by a little old lady.

Chapter 1: A First Program Using C#

Lecture 18 Tao Wang 1

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output


11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards

Object-Oriented Design Lecture 21 CSU 370 Fall 2008 (Pucella) Tuesday, Dec 9, 2007

Justification for Names and Optional Parameters

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

JAVA: A Primer. By: Amrita Rajagopal

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

CS 231 Data Structures and Algorithms, Fall 2016

CS112 Lecture: Working with Numbers

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Intro. Scheme Basics. scm> 5 5. scm>

Chapter 10 Introduction to Classes

6.096 Introduction to C++

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

Self-review Questions

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays

C++ for Java Programmers

PIC 20A The Basics of Java

Java Collections Framework

INHERITANCE AND EXTENDING CLASSES

Mr G s Java Jive. #11: Formatting Numbers

JavaScript: Sort of a Big Deal,

1007 Imperative Programming Part II

Lesson 1A - First Java Program HELLO WORLD With DEBUGGING examples. By John B. Owen All rights reserved 2011, revised 2015

Variables. Data Types.

This is a talk given by me to the Northwest C++ Users Group on May 19, 2010.

Lecture 10: building large projects, beginning C++, C++ and structs

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Programming Language Concepts: Lecture 2

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS61A Notes Week 1A: Basics, order of evaluation, special forms, recursion

Thinking Functionally

BM214E Object Oriented Programming Lecture 8

Lecture 02, Fall 2018 Friday September 7

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

CS-202 Introduction to Object Oriented Programming

Annotation Hammer Venkat Subramaniam (Also published at

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 4 Defining Classes I

Formatting: Cleaning Up Data

A brief introduction to C++

Errors and Exceptions

Understanding Recursion

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Ch. 12: Operator Overloading

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

2 Sets. 2.1 Notation. last edited January 26, 2016

COMP6700/2140 Methods

Gearing Up for Development CS130(0)

Object-Oriented Programming, Iouliia Skliarova

Data Structures (list, dictionary, tuples, sets, strings)

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Transcription:

Import Statements, Instance Members, and the Default Constructor Introduction In this article from my free Java 8 course, I will be discussing import statements, instance members, and the default constructor. Instance Members vs. Static Members As you can see below, I have created the Person class, and within that class we have an instance variable called personname and an instance method called helloworld(). Our variables and methods are called the instance members of the class. Example 1 public String helloworld() { return Hello World ; So what is an instance? An instance is a single occurrence of an object. While there is only one class, there are many instances of the class: objects. For example, we can have hundreds and hundreds of different Person objects. Each Person object has its own instance of the personname object, each with its own value and its own version of the helloworld() method. Besides instance variables and methods, there can also be static ones. All instances of a class share the static variables or static methods of the class. Variables and method are also called members. A member that belongs to the instance, is called instance member; a member that belongs to the class (a static variable or method) is called class member.

Besides instance members there are also static members, or class members. Class variables and methods are created by adding the static keyword to a method or variable. Example 2 private static Planet homeplanet; public static String helloworld() { return Hello World ; If we change the homeplanet value for one instance of Person, all of the other instances will have their values changed as well. This is an advanced topic that will be discussed later in more detail. For now, just know that without the static keyword, our methods and variables are instance variables and methods. Constructors Example 3 The next thing we will do in our program is write a constructor for our Person Object. I ve mentioned constructors before, but to go into more detail, constructors are the code that is used to create objects. Constructors start with the short name of the class, followed by parentheses, that contain any parameters, and then an opening curly brace and a closing curly brace. In between the curly braces you assign values to instance variables and call any methods that need to be called when an object of this class type is created. Constructors may look like methods, but they neither return a value nor do they have the tag void. You can have as many constructors as you want in a class, but each constructor needs a unique set of parameters.

If you don t write a constructor for your class, the compiler will automatically include a constructor that contains no parameters. This constructor is called the default constructor. This is a bit problematic in my opinion. If you do (at a later time) add a constructor that does contain one or more parameters, the default constructor will not be added by the compiler. I refer to such automatic compiler actions as magic, as they are not always clear and easily lead to confusion. Therefore, I generally recommend that you always write out your default constructor in code, if you need it. Never rely on the compiler to add it for you. However, this may lead to further confusion about why you added a redundant default constructor. Another developer might even just "extend" it later, adding parameters to the default constructor- effectively removing it from your class. So I suggest you use the following approach by default: if you need a default constructor, add it explicitly. Then leave a comment documenting why you explicitly added the default constructor in this case. To give a concrete example: default constructors are often needed when certain frameworks are in use, like Hibernate, for instance. For our Person class, I'm going to create a constructor that sets the value of personname given a value. If you look at the example below, I've created two different variables called personname. One of them is the instance variable in the class, and one of them is an argument in our constructor. To differentiate them, we have to add this. to the instance variable personname. This way this.personname is set to the personname received as an argument in the constructor. Example 4 private static Planet homeplanet; public Person(Name personname) { this.personname = personname; public static String helloworld() { return Hello World ;

Since we ve created a constructor, the compiler won t automatically use a default constructor. Now whenever someone calls the constructor to create an object of type person, they have to include the personname since that is the only constructor available to them. If you remember from our test class from last article, we constructed our object without any arguments. If we try to execute this test again, it will fail. Test Case Creation As I ve talked about before, a test method is annotated with @Test. This annotation invokes the Test class from the JUnit framework and sets up a test environment in our Java Virtual Machine (JVM). Let s create a second method in our test class so we can see how how our test class works a little more in depth. In our test class, I m going to create a second method, shouldreturnhellomarcus(). import org.junit.test; import static org.junit.assert.assertequals; public class PersonTest { @Test public void shouldreturnhelloworld() { Person person = new Person(); assertequals("hello World", person.helloworld() ); @Test public void shouldreturnhellomarcus() { Person marcus = new Person(); assertequals("hello Marcus", marcus.hello( Marcus )); Example 5 Once I ve created this method, I m going to create an object of type Person with an instance variable name of marcus. If we try to run this, we will get a compilation error as I noted earlier, because our shouldreturnhelloworld() method tries to create a Person object with a default constructor. To get rid of this error, we ll simply create a default constructor in our class.

Example 6 private static String homeplanet; public Person() { /* * default constructor, required by Hibernate */ Comments As I said before,there might be confusion later as to why you created this default constructor. You may even forget the reason yourself, further down the line. Adding comments to the code will prevent the confusion. They're ignored by the compiler so besides denoting the comment itself, little syntax is required. Do remember though to use comments sparingly, and never comment on the obvious. A variable person doesn t need a comment that says this is a person! Instead, you should always aim to express your intent in the code itself. For example, a method that adds two numbers that is called add() clearly portrays what it does and probably doesn t require a comment to describe the method. There are some few exceptions to this rule, but generally, a comment is used as a fix for bad code that doesn t properly express its intent. Comments can never be as precise as well written code. Also, while code is always up to date, a comment will usually end up out of sync with the code. Obsolete comments are really dangerous, they are often the cause for severe confusion. Therefore, I usually say comments lie and never completely trust a comment. Code can t lie. One will always be One and Zero will always be zero. Code always does exactly what it claims it does. There are two types of comments you can define in Java: multi-line comments and single line comments. Multi-line comments start with /* and end with */. Between these two symbols, you can write as many lines of comments as you d like.

A single line comment starts with // and lasts for the remainder of the line in the code. In general, I recommend that you always use multi-line comments, because if a single line comment is too long, it will be broken up when the code gets auto formatted, which might happen quite often in a development team. Now we create the default constructor for the class Person. Inside the default constructor I ve added a comment. I m also going to create the hello() method that we called in our test class. It receives one argument, which is the name of person we are saying hello to. Concatenating Strings In our hello() method we are returning a String. However, the String we return will not always be the same. It will always start with Hello, followed by the name of the person. We have to turn these two separate Strings into one String that we return. This process of adding Strings together is called Concatenation. To do this, we put a + between the two Strings, creating one larger String. Now our method will return Hello followed by the person s name. I ve left a hidden bug in Example 6 that will cause our test to fail. See if you can find it. Testing our Code and Fixing Bugs Now let s execute our Test class. It failed as expected. The reason is that there is a mismatch between our expected value which was Hello Marcus and the actual value, HelloMarcus. When we concatenated our two Strings we forgot to include a space between them. To fix this, all we have to do is add a space after the word Hello. public static String hello(string name) { return Hello + name; Example 7 Now when we execute our test, it s green and we ve successfully completed this article! Thanks for reading! 2017, Marcus Biel, Software Craftsman https://cleancodeacademy.com All rights reserved. No part of this article may be reproduced or shared in any manner whatsoever without prior written permission from the author