class objects instances Fields Constructors Methods static

Similar documents
BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

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

Java Bytecode (binary file)

Some Patterns for CS1 Students

CS 231 Data Structures and Algorithms, Fall 2016

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Beginning Style. 16-Nov-15

Notes on Chapter Three

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Fall 2017 CISC124 9/16/2017

CS11 Java. Fall Lecture 1

CSE 230 Intermediate Programming in C and C++ Functions

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

( &% class MyClass { }

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.

Coding Standards for Java

Object Oriented Programming. Week 1 Part 1 An introduction to Java, Objects and JUnit

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

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

Lab # 2. For today s lab:

Chapter 4 Defining Classes I

CS 177 Recitation. Week 1 Intro to Java

CS S-08 Arrays and Midterm Review 1

Condensed Java. 12-Oct-15

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

APCS Semester #1 Final Exam Practice Problems

CS 251 Intermediate Programming Coding Standards

JAVA: A Primer. By: Amrita Rajagopal

You must declare all variables before they can be used. Following is the basic form of a variable declaration:

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

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE. Speaking the Language of OO

CS 302: INTRODUCTION TO PROGRAMMING IN JAVA. Chapter 5: Methods. Lecture 10

Lecture 02, Fall 2018 Friday September 7

Assignment Marking Criteria

Mr. Monroe s Guide to Mastering Java Syntax

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

CSE 142/143 Unofficial Style Guide

1B1b Classes in Java Part I

Full file at

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

Repetition with for loops

Write for your audience

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Lecture 6 Introduction to Objects and Classes

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Ticket Machine Project(s)

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Section 2.2 Your First Program in Java: Printing a Line of Text

Give one example where you might wish to use a three dimensional array

CS 177 Recitation. Week 8 Methods

We will work with Turtles in a World in Java. Seymour Papert at MIT in the 60s. We have to define what we mean by a Turtle to the computer

CS 152 Computer Programming Fundamentals Coding Standards

Software Design and Analysis for Engineers

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

More Control Structures

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CS111: PROGRAMMING LANGUAGE II

CS 102 / CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2010

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

S206E Lecture 19, 5/24/2016, Python an overview

Part 2: The Material PART 2

ITI Introduction to Computing II

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Object Oriented Programming

Principles of Object Oriented Programming. Lecture 4

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

CPS122 Lecture: Defining a Class

Lecture 3. Lecture

D Programming Language

Program Fundamentals

Constants, References

CS 351 Design of Large Programs Coding Standards

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

AP CS Unit 3: Control Structures Notes

c) And last but not least, there are javadoc comments. See Weiss.

Boolean Expressions. Is Equal and Is Not Equal

Rules and syntax for inheritance. The boring stuff

1. Find the output of following java program. class MainClass { public static void main (String arg[])

C++ Programming Style Guide

Arrays Classes & Methods, Inheritance

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Boolean Expressions. Is Equal and Is Not Equal

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

Methods and Data (Savitch, Chapter 5)

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Mobile App:IT. Methods & Classes

Semantic Analysis. Lecture 9. February 7, 2018

PROGRAMMING STYLE. Fundamentals of Computer Science I

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Transcription:

Class Structure

Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance variables)that hold the data for each object Constructors that tell how to create a new object of this class Methods that describe the actions the object can perform In addition, a class can have data and methods of its own (not part of the objects) For example, it can keep a count of the number of objects it has created Such data and methods are called static Similar to Python class methods Will come back to these later

Defining a class Here is the simplest syntax for defining a class: class ClassName { // the fields (variables) of the object // the constructors for the object // the methods of the object You can put public, protected, private or no modifier before the word class Default is protected This basically defines the visibility of the class public means any program in the project can use (i.e., create objects/call methods) that class protected means only programs in the same package and subclasses in other packages can use the class no modifier means only programs in the same package can use the class private means only methods within that class can use the class Things in a class can be in any order Eclipse example: PezDispenser.java

Defining fields An object s data is stored in fields (also called instance variables) The fields describe the state of the object Fields are defined with ordinary variable declarations: String name; double health; int age = 0; Instance variables are available throughout the entire class that declares them Eclipse example: PezDispenser.java

Defining constructors A constructor is code to create an object Similar to Python s init method You can do other work in a constructor, but you shouldn t The syntax for a constructor is: ClassName(parameters) { code The ClassName has to be the same as the class that the constructor occurs in The parameters are a comma-separated list of variable declarations Eclipse example: PezDispenser.java

Defining a method A method has the syntax: return-type method-name(parameters) { method-variables code Eclipse example: PezDispenser.java

Returning a result from a method If a method is to return a result, it must specify the type of the result You must use a return statement to exit the method with a result of the correct type Eclipse example: PezDispenser.java

Returning no result from a method The keyword void is used to indicate that a method doesn t return a value The return statement must not specify a value There are two ways to return from a void method: Execute a return statement Reach the closing brace of the method Eclipse example: PezDispenser.java

Creating an object An object is also called an instance of a class You create an object of by calling its constructor and using the keyword new Syntax class ClassName{ public ClassName(par1, parn){ //some statements public static void main(string[] args){ ClassName c = new ClassName(arg1,, argn); Note: new creates a new object on the heap The object name is a pointer to that object (surprise, surprise) Eclipse example: PezDispenser.java

Sending messages to objects We don t perform operations on objects, we talk to them This is called sending a message to the object A message looks like this: object.method(extra information) The object is the thing we are talking to The method is a name of the action we want the object to take The extra information is anything required by the method in order to do its job Eclipse example: PezDispenser.java

Methods may have local variables A method may have local (method) variables Formal parameters are a kind of local variable int add(int m, int n) { int sum = m + n; return sum; m, n, and sum are all local variables The scope of m, n, and sum is the method These variables can only be used in the method, nowhere else The names can be re-used elsewhere, for other variables

Blocks (== Compound statements) Inside a method or constructor, whenever you use braces, you are creating a block, or compound statement: int absolutevalue(int n) { if (n < 0) { return -n; else return n; As with if-cases, you don t need braces if your method is just one statement

Declarations in a method The scope of formal parameters is the entire method The scope of a variable in a block starts where you define it and extends to the end of the block if (x > y) { int larger = x; else { int larger = y; return larger; larger larger scope of larger scope of a different larger Illegal: not declared in current scope

Nested scopes int fibonacci(int limit) { int first = 1; int second = 1; while (first < 1000) { System.out.print(first + " "); int next = first + second; first = second; second = next; next System.out.println( ); second first limit

The for loop The for loop is a special case You can declare variables in the for statement The scope of those variables is the entire for loop This is true even if the loop is not a block void multiplicationtable() { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) System.out.print(" " + i * j); System.out.println(); j i

Methods and static methods Java has two kinds of methods: static methods and non-static methods (called instance methods) Static methods are Java s equivalent to class methods in Python You call them using the class, not the object They do not have access to instance variables Most methods you write should not be static Every Java program has a main method, which is static Static methods should be used for operations that do not depend on instance variables or objects Eclipse example: Arithmetic.java

null If you declare a variable to have a given object type, for example, Person john; String name;...and if you have not yet assigned a value to it, for example, with john = new Person(); String name = John Smith";...then the value of the variable is null null is a legal value, but there isn t much you can do with it It s an error to refer to its fields, because it has none It s an error to send a message to it, because it has no methods null is basically a pointer that doesn t point to anything (with value 0) Very similar to Python s None The error you will see is NullPointerException

Visibility Older languages greatly emphasized the notion of visibility Especially Java and C/C++ Visibility determines how accessible is your class/method/variable Discussed class visibility earlier Same idea for methods and variables Usually it is a good idea to make you instance variables private Don t want other people to arbitrarily change them Instead, expose methods for modifying instance variables Can also have private methods You don t want anyone but you to use these they are for some internal computations in your program Will see examples of these later in the class Eclipse example: PezDispenserPrivate.java

Java style As with Python, the more important thing is to be consistent Anyway, here are some Java conventions Naming is camelcase Variable names start with a lowercase letter Class names start with a capital letter Indentation is 2 or 4 spaces (no consensus here) I think 4 looks better (but won t take off points for 2 as long as you are consistent) In Java indentation is style, so make sure you indent! Braces go on the same line as the method/loop definition In C, they go on the next line on their own As always, you should have many comments