24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
11-Jun-15 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand.
Access to Names Namespaces, Scopes, Access privileges.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
Java: How to Program Methods Summary Yingcai Xiao.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
20-Jun-15 Methods. Complexity The programmer's biggest adversary is complexity The programmer's biggest adversary is complexity Primitive types and the.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling the.
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
30-Jun-15 Static Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
16-Jul-15 Access. 2 Overview Questions covered in this talk: How do we access fields and methods? Why have access restrictions? What can have access restrictions?
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
COMP More About Classes Yi Hong May 22, 2015.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
Basic Object- Oriented Concepts Presented By: George Pefanis 21-Sep-15.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
1 Objects and Classes. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity.
Methods. 2 A sequence of statements can be packaged together as a unit and re-used. A method is a named unit of re-usable code. modifier returnType methodName(
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Introduction to programming in the Java programming language.
ECE122 Feb. 22, Any question on Vehicle sample code?
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
1 Programming Week 2 2 Inheritance Basic Java Language Section.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
Objects and Classes Mostafa Abdallah
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
OOP Basics Classes & Methods (c) IDMS/SQL News
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Functions + Overloading + Scope
Topic: Classes and Objects
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Suppose we want to print out the word MISSISSIPPI in big letters.
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Namespaces, Scopes, Access privileges
Static Methods 14-Nov-18.
Class Structure 16-Nov-18.
Classes, Objects, and Methods
An Introduction to Java – Part I, language basics
Class Structure 28-Nov-18.
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
Classes Lecture 7 from Chapter /1/11.
Namespaces, Scopes, Access privileges
Class Structure 25-Feb-19.
Classes, Objects and Methods
Announcements Assignment 2 and Lab 4 due Wednesday.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Corresponds with Chapter 5
Classes and Methods 15-Aug-19.
Presentation transcript:

24-Dec-15 Class Structure

2 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 We are avoiding static data and methods for the time being

3 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, or private before the word class Things in a class can be in any order (I recommend the above order)

4 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

5 Defining constructors A constructor is code to create an object 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

6 Example constructor I public class Person { String name; int age; boolean male; Person (String aName, boolean isMale) { name = aName; male = isMale; } } Constructor Parameters

7 Example constructor II Most constructors just set instance variables: public class Person { String name; boolean male; Person (String name, boolean male) { this.name = name ; this.male = male ; } }

Defining a method A method has the syntax: return-type method-name ( parameters ) { method-variables code } Example: boolean isAdult(int age) { int magicAge = 21; return age >= magicAge; } Example: double average(int a, int b) { return (a + b) / 2.0; }

9 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

10 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; }

11 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 scope of larger larger scope of a different larger Illegal: not declared in current scope

12 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; } System.out.println( ); } limit first next second

13 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

Returning a result from a method If a method is to return a result, it must specify the type of the result: boolean isAdult ( … You must use a return statement to exit the method with a result of the correct type: return age >= magicAge ;

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 Example: void printAge(String name, int age) { System.out.println(name + " is " + age + " years old."); return; }  There are two ways to return from a void method:  Execute a return statement  Reach the closing brace of the method

16 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 Examples: g.setColor(Color.pink); amountOfRed = Color.pink.getRed( );

17 Putting it all together class Person { // fields String name; int age; // constructor Person(String name) { this.name = name; age = 0; } // methods String getName() { return name; } void birthday() { age = age + 1; System.out.println( "Happy birthday!"); } }

18 Using our new class Person john; john = new Person("John Smith"); System.out.print (john.getName()); System.out.println(" is having a birthday!"); john.birthday();  Of course, this code must also be inside a class!

19 Diagram of program structure A program consists of one or more classes Typically, each class is in a separate.java file Program File Class Variables Constructors Methods Variables Statements

20 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 The error you will see is NullPointerException

Methods and static methods Java has two kinds of methods: static methods and non-static methods (called instance methods) However, before we can talk about what it means to be static, we have to learn a lot more about classes and objects Most methods you write should not, and will not be static Every Java program has a public static void main(String[ ] args) method This starts us in a “static context” To “escape from static”, I recommend starting every program in a certain way, as shown on the next slide

Escaping from static class MyClass { public static void main(String[] args) { new MyClass().run(); } void run() { // Your real code begins here } } You can replace the names MyClass and run with names of your choice, but notice that each name occurs in two places, and they have to match up 22

The End The problem with object-oriented languages is they've got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. — Joe Armstrong Though this be madness, yet there is method in it. — Shakespeare, Hamlet