Software Development Java Classes and Methods

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Python Objects and Classes
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Computer Science 209 Software Development Equality and Comparisons.
Written by: Dr. JJ Shepherd
1 Object Oriented Programming mr. Hanley. 2 Programs built from smaller components Today’s software programs are generally built from pieces of code known.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Information Hiding and Encapsulation
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.
P Chapter 2 introduces Object Oriented Programming. p OOP is a relatively new approach to programming which supports the creation of new data types and.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Day Class Definitions and Methods Local & global variables, parameters & arguments,
David Streader & Peter Andreae Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Objects.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 5 Introduction to Defining Classes
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Object Oriented Programming
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Computer Science 209 Software Development Handing Errors and Creating Documentation.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Inheritance and Polymorphism
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
1 Guide gus; Creates a “mailbox” to hold the address of a Guide object. null gus.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Object-Oriented Concepts
Object Oriented Programming
Chapter 11 Inheritance and Polymorphism
Object Oriented Programming
Intro To Classes Review
Software Development Handing Errors and Creating Documentation
Section 11.1 Class Variables and Methods
CS 302 Week 11 Jim Williams, PhD.
Computer Science II Exam 1 Review.
Interfaces and Constructors
Implementing Classes Chapter 3.
Defining Classes and Methods
Object-Oriented Programming
CIS 199 Final Review.
TCSS 143, Autumn 2004 Lecture Notes
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Software Development Java Classes and Methods Computer Science 209 Software Development Java Classes and Methods

Objects, Classes, and Methods There are no functions in Java, only methods There are instance methods and class methods Built-in classes include String, Math, and Arrays Classes in libraries include a host of collections, file streams, resources for GUIs, networks, concurrency, etc.

Example: A Student Class A student has a name and a set of test scores The name can be accessed and reset Scores can be accessed and reset by position, counting from 1 The high score and the average score can be accessed Constructors and string representation are available

Default Instantiation and String Representation Student s = new Student(); System.out.println(s); Name: Scores: Defaults are an empty name string and 3 scores of 0

User-Specified Instantiation and String Representation Student s = new Student("Ken", 5); System.out.println(s); Name: Ken Scores: Defaults can be overridden with another constructor

Access and Mutate Student s = new Student("Ken", 5); for (int i = 1; i <= 5; i++) // Set all scores to 100 s.setScore(i, 100); System.out.println("Average: " + s.getAverageScore()); System.out.println("High: " + s.getHighScore()); Average: 100.0 High: 100

Python Class Definition class Student(object): # Class variable DEFAULT_NUM_SCORES = 3 # Constructor def __init__(self, nm = "", numScores = None): self.name = nm if numScores: self.scores = Array(numScores) else: self.scores = Array(Student.DEFAULT_NUM_SCORES) # String representation def __str__(self): result = "Name: " + self.name + "\nScores:\n" for score in self scores: result += str(score) + "\n" result += "Average: " + getAverage(); return result

Java Class Definition public class Student extends Object{ // Class variable static public final int DEFAULT_NUM_SCORES = 3; static variables hold data shared by all instances of the class final variables behave like constants Constants use all caps and underscores

Java Class Definition public class Student{ // Class variable static public final int DEFAULT_NUM_SCORES = 3; // Instance variables private String name; private int[] scores; Instance variables hold data that belong to each individual object Instance variables are declared at the same level as methods Instance variables are normally declared private

Java Class Definition Constructors can be chained public class Student{ // Class variable static public final int DEFAULT_NUM_SCORES = 3; // Instance variables private String name; private int[] scores; // Constructors public Student(String nm, int numScores){ name = nm; scores = new int[numScores]; } public Student(){ this("", DEFAULT_NUM_SCORES); Constructors can be chained

Access Modifiers For now, all methods should be declared as public For now, all instance variables should be declared as private For now, all class (static) variables should be declared as public final

Pubic, Private, Static, and Final public – anyone can access the item private – access only within the class definition static – the item belongs to the class, not to its instances final – you can initialize but not reset the item

The toString Method // String representation public String toString(){ String str = "Name: " + name + "\nScores:\n"; for (int score : scores) str += score + "\n"; str += "Average: " + getAverage(); return str; } Java automatically runs toString on arguments to println

Accessor Methods Just observe state without changing it public String getName(){ return name; } public int getScore(int i){ return scores[i - 1]; public int getNumScores(){ return scores.length; Just observe state without changing it

Mutator Methods Change the state! public void setName(String nm){ name = nm; } public void setScore(int i, int newScore){ scores[i - 1] = newScore; Change the state!

Mutator Methods Change the state! public void setName(String nm){ name = nm; } public void setScore(int i, int newScore){ scores[i - 1] = newScore; Change the state! Because scores has been declared private, it can only be accessed or modified by running getScore or setScore (data encapsulation)

Equality public boolean equals(Object other){ if (this == other) return true; if (! (other instanceof Student)) return false; Student s = (Student) other; return this.name.equals(s.name); } The Object class is the root class in the Java class hierarchy. You can assign any object to a variable or parameter of type Object Check identity type structure

Comparisons and Ordering public interface Comparable<T>{ // Returns 0 if receiver equals other // Returns < 0 if receiver is less than other // Returns > 0 if receiver is greater than other public int compareTo(T other); } public class Student implements Comparable<Student>{ public int compareTo(Student other){ return this.name.compareTo(other.name); } … More strict than equals; type errors are caught at compile time

Now Do Sorting and Searching Student [] students = new Student[10]; // Add 10 Student objects to the array java.util.Arrays.sort(students); Student target = new Student("ken", 10)); int position = java.util.Arrays.binarySearch(students, target); The element type in the array must implement the Comparable interface

Preconditions Postconditions Exceptions Javadoc For next time Preconditions Postconditions Exceptions Javadoc