Designing and Implementing Classes Topic 6

Total Page:16

File Type:pdf, Size:1020Kb

Designing and Implementing Classes Topic 6 Object Oriented Programming Designing and Object Oriented Programming is not new. – Simula 1 (1962 - 1965) and Simula 67 (1967) Norwegian Implementing Classes Computing Center, Oslo, Norway by Ole-Johan Dahl and Kristen Nygaard. Topic 6 – Smalltalk (1970s), Alan Kay's group at Xerox PARC – C++ (early 1980s), Bjarne Stroustrup, Bell Labs Don't know much geography – Eiffel, Bertrand Meyer Don't know much trigonometry – Java and others Don't know much about algebra Becoming the dominant style for implementing Don't know what a slide rule is for complex programs with large numbers of -Sam Cooke interacting components and in education AP Computer Science Designing and Implementing Classes 1 AP Computer Science Designing and Implementing Classes 2 Tenants of Object Oriented Main Tenets of OO Programming Programming - Encapsulation Encapsulation information hiding, using something without – abstraction, information hiding, responsibility knowing (or caring or having to worry) about driven programming how it works. abstraction Inheritance achieved via classes and objects. Useful in – code reuse, specialization breaking up large problems based on a study Polymorphism of the data involved first – allows old code to use new code, do X, where X Don Knuth, Turing award winner is different depending on the type of object algorithms + data structures = programming AP Computer Science Designing and Implementing Classes 3 AP Computer Science Designing and Implementing Classes 4 Class and Objects Using Objects What are classes? An object is a model (abstraction of) a real- – classes are user defined data types. (as opposed to the primitive data types) world object. – classes specify the operations that may be carried out on – it is a collection of variables (fields) and methods variables of this type. Behaviors A method is an operation on an object. – They also specify what sub data the variable consists of and have the implementation of the behaviors listed Objects interact with messages. A message above. is sent to an object and specifies the method – objects are simply variables of a given class that object should perform. It is easier to describe how to use an object than it – The sender (normally another object) doesn't is to create a class know anything about how the method is – easier to teach some one to drive car or teach someone performed how to design and build a car? AP Computer Science Designing and Implementing Classes 5 AP Computer Science Designing and Implementing Classes 6 Using Objects The dot Operator Objects are variables, they have a declared type Once an object is created the dot operator and a set of behaviors or operations ( . ) is used to perform operations on the object or access sub data in the object String name1 = new String("Olivia A. Scott"); String name2 = new String("Isabelle M. Scott"); String name1 = new String("Olivia A. Scott"); char first = name1.charAt(0); All object variables are reference variables (i.e. char second = name2.charAt(1); pointers) Any public part of the object may be accessed. Objects must be dynamically allocated using the normally only methods are public. new operator and calling a constructor – Must call a method that actually exists and match one of – special cases for Strings and arrays the parameter signatures or syntax error To determine the various behaviors of an object the dot operator calls or invokes the method must look at the class documentation flow of control shifts to that code AP Computer Science Designing and Implementing Classes 7 AP Computer Science Designing and Implementing Classes 8 Object Data Object Methods occasionally fields of an object are public, but this Object methods either is generally considered bad style – tell you something about the object array length vs. String length • accessors, have a return value int[] list = new int[x]; • the charAt and length methods in String for(int i = 0; i < list.length; i++) – change the object in some way Only a good idea if the data is constant. • mutators, no return value. Changes the state of the Good object oriented programming style calls for object any changes to an object to be done via a method • the setSize method in Rectangle call – do both, some people consider this bad style Normally a data's object is hidden (encapsulated) • mutators that return a value, return value and a and if I am using an object I don't know or care change to the object's state about the details of that implementation AP Computer Science Designing and Implementing Classes 9 AP Computer Science Designing and Implementing Classes 10 Finding Object Methods Classes fundamental unit of OO programming JavaTM 2 Platform, Standard Edition, v 1.4.x API Specification Java programs of any significance are a – Your best friend in the world collection of classes http://java.sun.com/j2se/1.4.1/docs/api/ Has specification for all classes in the Java standard library This is a rather smallish Only documents the public portion, what we program and it contains can use! 6 classes not counting another 6 classes from A product of javadoc the Java Standard Library java source code in -> easy to read html out AP Computer Science Designing and Implementing Classes 11 AP Computer Science Designing and Implementing Classes 12 What are Classes? More on Classes classes are blueprints Each class in Java is contained in its own file with the name – they specify what new objects will contain and what matching the class name and with the .java extension can be done to the objects The basics elements of a class are – classes are analogous to data types and objects are – constructors • used in the creation of objects. Similar to methods (procedures and the variables of that type functions). classes consist of an interface (what is it?) and • Normally several overloaded for the convenience of the class users an implementation (how it is done?) – methods • instance methods and class (static) methods – interface describes the ways an object of this type may – variables (or fields) be created via constructors and how a client may use • instance variables and class variables (static) or manipulate an object of this type via methods – constants – implementation is hidden and of no concern to the • instance (rare) and class (static) client. implementation can be changed without affecting any client code AP Computer Science Designing and Implementing Classes 13 AP Computer Science Designing and Implementing Classes 14 The Die Class The Die Class Interface Consider a class used Constructors (used in creation of objects) to model a die – default, single int parameter to specify the What is the interface? What number of sides, int and boolean to determine if actions should a die be able should roll to perform? Mutators (change state of objects) –roll Accessors (do not change state of objects) – getTopSide, getNumSides, toString The methods or behaviors can be broken up Public constants into constructors, mutators, accessors – DEFAULT_SIDES AP Computer Science Designing and Implementing Classes 15 AP Computer Science Designing and Implementing Classes 16 Visibility Modifiers The Die Class Implementation All parts of a class have visibility modifiers Implementation is made up of constructor code, method code, and private data members of the – Java keywords class. – public, protected, private, (no modifier means package access) scope of data members / instance variables – private data members may be used in any of the – do not use these modifiers on local variables (syntax error) constructors or methods of a class public means that constructor, method, or field may Implementation is hidden from users of a class and be accessed outside of the class. can be changed without changing the interface or – part of the interface affecting clients (other classes that use this class) – constructors and methods are generally public – Example: Previous version of Die class, private means that part of the class is hidden and DieVersion1.java Once Die class completed can be used in anything inaccessible by code outside of the class requiring a Die or situation requiring random – part of the implementation numbers between 1 and N – data fields are generally private – DieTester class. What does it do? AP Computer Science Designing and Implementing Classes 17 AP Computer Science Designing and Implementing Classes 18 DieTester method DieTester continued int total = 0; int numRolls = 0; public static void main(String[] args) { do final int NUM_ROLLS = 50; { d1.roll(); final int TEN_SIDED = 10; d2.roll(); Die d1 = new Die(); d3.roll(); Die d2 = new Die(); total = d1.getTopSide() + d2.getTopSide () Die d3 = new Die(TEN_SIDED); + d3.getTopSide (); final int MAX_ROLL = d1.getNumSides() + numRolls++; d2.getNumSides() + d3.getNumSides(); } while(total != MAX_ROLL); for(int i = 0; i < NUM_ROLLS; i++) System.out.println("\n\nNumber of rolls to get " { d1.roll(); + MAX_ROLL + " was " + numRolls); d2.roll(); System.out.println("d1: " + d1.getResult() + " d2: " + d2.getTopSide() + " Total: " + (d1.getTopSide() + d2.getTopSide() ) ); } AP Computer Science Designing and Implementing Classes 19 AP Computer Science Designing and Implementing Classes 20 The Steps of Class Design Correctness Sidetrack Requirements When creating the public interface of a class give – what is the problem to be solved careful thought and consideration to the contract – detailed requirements lead to specifications you are creating between yourself and users (other Nouns may be classes programmers) of your class Use preconditions to
Recommended publications
  • 18-Variables.Pdf
    Mehran Sahami Handout #18 CS 106A October 12, 2007 Variables, variables, everywhere… Based on a handout by Patrick Young. Local Variables Local variables are created local to the method (or the block—see “Block Scope” section below) in which they are defined. They are destroyed when execution of the method has been completed. Local variables can only be accessed from within the method in which they are declared. Because of their transient nature, local variables cannot store persistent information about an object between method calls. Local Variables Example Consider, for example, the following snippet of code. class AnExample extends ConsoleProgram { public void methodOne { int a = readInt("Enter a: "); println("a = " + a); } public void methodTwo { int b = a; // BUG!: cannot refer to variable a in methodOne println("b = " + b); } } The variables a and b are local variables declared within different methods in the class AnExample . Because these variables are local variables, a can only be referred to within methodOne and variable b can only be accessed within methodTwo . Our attempt to initialize b using the value of a is illegal, as code in methodTwo cannot access local variables from methodOne or any other method. Because local variable values do not persist after their containing method has completed, the variable a will be destroyed when methodOne has completed execution. The next time methodOne is called, a new variable a will be created. Block Scope While we typically think of local variables as local to a particular method, in Java local variables are actually local to a block of code. While a method defines a block of code (since the opening and closing braces of the method define a block), for and while loops, if -statements, and other constructs are also considered blocks of code.
    [Show full text]
  • Thriving in a Crowded and Changing World: C++ 2006–2020
    Thriving in a Crowded and Changing World: C++ 2006–2020 BJARNE STROUSTRUP, Morgan Stanley and Columbia University, USA Shepherd: Yannis Smaragdakis, University of Athens, Greece By 2006, C++ had been in widespread industrial use for 20 years. It contained parts that had survived unchanged since introduced into C in the early 1970s as well as features that were novel in the early 2000s. From 2006 to 2020, the C++ developer community grew from about 3 million to about 4.5 million. It was a period where new programming models emerged, hardware architectures evolved, new application domains gained massive importance, and quite a few well-financed and professionally marketed languages fought for dominance. How did C++ ś an older language without serious commercial backing ś manage to thrive in the face of all that? This paper focuses on the major changes to the ISO C++ standard for the 2011, 2014, 2017, and 2020 revisions. The standard library is about 3/4 of the C++20 standard, but this paper’s primary focus is on language features and the programming techniques they support. The paper contains long lists of features documenting the growth of C++. Significant technical points are discussed and illustrated with short code fragments. In addition, it presents some failed proposals and the discussions that led to their failure. It offers a perspective on the bewildering flow of facts and features across the years. The emphasis is on the ideas, people, and processes that shaped the language. Themes include efforts to preserve the essence of C++ through evolutionary changes, to simplify itsuse,to improve support for generic programming, to better support compile-time programming, to extend support for concurrency and parallel programming, and to maintain stable support for decades’ old code.
    [Show full text]
  • Declare Constant in Pseudocode
    Declare Constant In Pseudocode Is Giavani dipterocarpaceous or unawakening after unsustaining Edgar overbear so glowingly? Subconsciously coalitional, Reggis huddling inculcators and tosses griffe. Is Douglas winterier when Shurlocke helved arduously? An Introduction to C Programming for First-time Programmers. PseudocodeGaddis Pseudocode Wikiversity. Mark the two inputs of female students should happen at school, raoepn ouncfr hfofrauipo io a sequence of a const should help! Lab 61 Functions and Pseudocode Critical Review article have been coding with. We declare variables can do, while loop and constant factors are upgrading a pseudocode is done first element of such problems that can declare constant in pseudocode? Constants Creating Variables and Constants in C InformIT. I save having tax trouble converting this homework problem into pseudocode. PeopleTools 52 PeopleCode Developer's Guide. The students use keywords such hot START DECLARE my INPUT. 7 Look at evening following pseudocode and answer questions a through d Constant Integer SIZE 7 Declare Real numbersSIZE 1 What prospect the warmth of the. When we prepare at algebraic terms to propagate like terms then we ignore the coefficients and only accelerate if patient have those same variables with same exponents Those property which qualify this trade are called like terms All offer given four terms are like terms or each of nor have the strange single variable 'a'. Declare variables and named constants Assign head to an existing variable. Declare variable names and types INTEGER Number Sum. What are terms of an expression? 6 Constant pre stored value in compare several other codes. CH 2 Pseudocode Definitions and Examples CCRI Faculty.
    [Show full text]
  • Java Static Keyword
    This page was exported from - TechnicalStack Export date: Sun Sep 26 13:56:23 2021 / +0000 GMT Java static keyword Java static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static can be: - variable (also known as class variable) - method (also known as class method) - block - nested class 1) Java static variable If you declare any variable as static, it is known static variable. - The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. - The static variable gets memory only once in class area at the time of class loading. Advantage of static variable It makes your program memory efficient (i.e it saves memory). Understanding problem without static variable class Student{ int rollno; String name; String college="ITS"; } Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once. Java static property is shared to all objects. Example of static variable //Program of static variable class Student8{ int rollno; String name; static String college ="ITS"; Student8(int r,String n){
    [Show full text]
  • CS 61A A&S Section 3.0 Object-Oriented Programming
    CS 61A A&S Section 3.0 Object-Oriented Programming | Above the line view This document should be read before Section 3.1 of the text. A second document, \Object-Oriented Programming | Below the line view," should be read after Section 3.1 and perhaps after Section 3.2; the idea is that you first learn how to use the object-oriented programming facility, then you learn how it's implemented. Object-oriented programming is a metaphor. It expresses the idea of several independent agents inside the computer, instead of a single process manipulating various data. For example, the next programming project is an adventure game, in which several people, places, and things interact. We want to be able to say things like \Ask Fred to pick up the potstickers." (Fred is a person object, and the potstickers are a thing object.) Programmers who use the object metaphor have a special vocabulary to describe the components of an object-oriented programming (OOP) system. In the example just above, \Fred" is called an instance and the general category \person" is called a class. Programming languages that support OOP let the programmer talk directly in this vocabulary; for example, every OOP language has a “define class" command in some form. For this course, we have provided an extension to Scheme that supports OOP in the style of other OOP languages. Later we shall see how these new features are implemented using Scheme capabilities that you already understand. OOP is not magic; it's a way of thinking and speaking about the structure of a program.
    [Show full text]
  • Java: Odds and Ends
    Computer Science 225 Advanced Programming Siena College Spring 2020 Topic Notes: More Java: Odds and Ends This final set of topic notes gathers together various odds and ends about Java that we did not get to earlier. Enumerated Types As experienced BlueJ users, you have probably seen but paid little attention to the options to create things other than standard Java classes when you click the “New Class” button. One of those options is to create an enum, which is an enumerated type in Java. If you choose it, and create one of these things using the name AnEnum, the initial code you would see looks like this: /** * Enumeration class AnEnum - write a description of the enum class here * * @author (your name here) * @version (version number or date here) */ public enum AnEnum { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } So we see here there’s something else besides a class, abstract class, or interface that we can put into a Java file: an enum. Its contents are very simple: just a list of identifiers, written in all caps like named constants. In this case, they represent the days of the week. If we include this file in our projects, we would be able to use the values AnEnum.MONDAY, AnEnum.TUESDAY, ... in our programs as values of type AnEnum. Maybe a better name would have been DayOfWeek.. Why do this? Well, we sometimes find ourselves defining a set of names for numbers to represent some set of related values. A programmer might have accomplished what we see above by writing: public class DayOfWeek { public static final int MONDAY = 0; public static final int TUESDAY = 1; CSIS 225 Advanced Programming Spring 2020 public static final int WEDNESDAY = 2; public static final int THURSDAY = 3; public static final int FRIDAY = 4; public static final int SATURDAY = 5; public static final int SUNDAY = 6; } And other classes could use DayOfWeek.MONDAY, DayOfWeek.TUESDAY, etc., but would have to store them in int variables.
    [Show full text]
  • (8 Points) 1. Show the Output of the Following Program: #Include<Ios
    CS 274—Object Oriented Programming with C++ Final Exam (8 points) 1. Show the output of the following program: #include<iostream> class Base { public: Base(){cout<<”Base”<<endl;} Base(int i){cout<<”Base”<<i<<endl;} ~Base(){cout<<”Destruct Base”<<endl;} }; class Der: public Base{ public: Der(){cout<<”Der”<<endl;} Der(int i): Base(i) {cout<<”Der”<<i<<endl;} ~Der(){cout<<”Destruct Der”<<endl;} }; int main(){ Base a; Der d(2); return 0; } (8 points) 2. Show the output of the following program: #include<iostream> using namespace std; class C { public: C(): i(0) { cout << i << endl; } ~C(){ cout << i << endl; } void iSet( int x ) {i = x; } private: int i; }; int main(){ C c1, c2; c1.iSet(5); {C c3; int x = 8; cout << x << endl; } return 0; } (8 points) 3. Show the output of the following program: #include<iostream> class A{ public: int f(){return 1;} virtual int g(){return 2;} }; class B: public A{ public: int f(){return 3;} virtual int g(){return 4;} }; class C: public A{ public: virtual int g(){return 5;} }; int main(){ A *pa; A a; B b; C c; pa=&a; cout<<pa -> f()<<endl; cout<<pa -> g()<<endl; pa=&b; cout<<pa -> f() + pa -> g()<<endl; pa=&c; cout<<pa -> f()<<endl; cout<<pa -> g()<<endl; return 0; } (8 points) 4. Show the output of the following program: #include<iostream> class A{ protected: int a; public: A(int x=1) {a=x;} void f(){a+=2;} virtual g(){a+=1;} int h() {f(); return a;} int j() {g(); return a;} }; class B: public A{ private: int b; public: B(){int y=5){b=y;} void f(){b+=10;} void j(){a+=3;} }; int main(){ A obj1; B obj2; cout<<obj1.h()<<endl; cout<<obj1.g()<<endl; cout<<obj2.h()<<endl; cout<<obj2.g()<<endl; return 0; } (10 points) 5.
    [Show full text]
  • Topic 5 Implementing Classes Definitions
    Topic 5 Implementing Classes “And so,,p,gg from Europe, we get things such ... object-oriented analysis and design (a clever way of breaking up software programming instructions and data into Definitions small, reusable objects, based on certain abtbstrac tion pri nci ilples and dd desig in hierarchies.)” -Michael A . Cusumano , The Business Of Software CS 307 Fundamentals of Implementing Classes 1 CS 307 Fundamentals of Implementing Classes 2 Computer Science Computer Science Object Oriented Programming Classes Are ... What is o bject or iente d programm ing ? Another, simple definition: "Object-oriented programming is a method of A class is a programmer defined data type. programmibing base d on a hihflhierarchy of classes, an d well-defined and cooperating objects. " A data type is a set of possible values and What is a class? the oper ati on s th at can be perf orm ed on those values "A class is a structure that defines the data and the methods to work on that data . When you write Example: programs in the Java language, all program data is – single digit positive base 10 ints wrapped in a class, whether it is a class you write – 1234567891, 2, 3, 4, 5, 6, 7, 8, 9 or a class you use from the Java platform API – operations: add, subtract libraries." – Sun code camp – problems ? CS 307 Fundamentals of Implementing Classes 3 CS 307 Fundamentals of Implementing Classes 4 Computer Science Computer Science Data Types Computer Languages come with built in data types In Java, the primitive data types, native arrays A Very Short and Incomplete Most com puter l an guages pr ovi de a w ay f or th e History of Object Oriented programmer to define their own data types Programming.
    [Show full text]
  • 10. Classes: an Initial Example
    10. Classes: An Initial Example This is the first chapter about classes. It is also the first chapter in the first lecture about classes. Our basic coverage of classes runs until Chapter 13. 10.1. The Die Class Lecture 3 - slide 2 In this section we encounter a number of important OOP ideas, observations, and principles. We will very briefly preview many of these in a concrete way in the context of a simple initial class. Later we will discuss the ideas in depth. We use the example of a die , which is the singular form of "dice", see Program 10.1. One of the teaching assistants in 2006 argued that the class Die is a sad beginning of the story about classes. Well, it is maybe right. I think, however, that the concept of a die is a good initial example. So we will go for it! On purpose, we are concerned with use of either the singular or the plural forms of class names. The singular form is used when we wish to describe and program a single phenomenon/thing/object. The plural form is most often used for collections, to which we can add or delete (singular) objects. Notice that we can make multiple instances of a class, such as the Die class. In this way we can create a number of dice. The class Die in Program 10.1 is programmed in C#. We program a die such that each given die has a fixed maximum number of eyes, determined by the constant maxNumberOfEyes . The class encapsulates the instance variables : numberOfEyes , randomNumberSupplier , and the constant maxNumberOfEyes .
    [Show full text]
  • Declare Class Constant for Methodjava
    Declare Class Constant For Methodjava Barnett revengings medially. Sidney resonate benignantly while perkier Worden vamp wofully or untacks divisibly. Unimprisoned Markos air-drops lewdly and corruptibly, she hints her shrub intermingled corporally. To provide implementations of boilerplate of potentially has a junior java tries to declare class definition of the program is assigned a synchronized method Some subroutines are designed to compute and property a value. Abstract Static Variables. Everything in your application for enforcing or declare class constant for methodjava that interface in the brave. It is also feel free technical and the messages to let us if the first java is basically a way we read the next higher rank open a car. What is for? Although research finds that for keeping them for emacs users of arrays in the class as it does not declare class constant for methodjava. A class contains its affiliate within team member variables This section tells you struggle you need to know i declare member variables for your Java classes. You extend only call a robust member method in its definition class. We need to me of predefined number or for such as within the output of the other class only with. The class in java allows engineers to search, if a version gives us see that java programmers forgetting to build tools you will look? If constants for declaring this declaration can declare constant electric field or declared in your tasks in the side. For constants for handling in a constant strings is not declare that mean to avoid mistakes and a primitive parameter.
    [Show full text]
  • C++ Fundamentals
    C++ Fundamentals Only what you need to know Outline • Part 1 – Basic Syntax Review – C++ Definitions, Source Code Organization, Building your Code • Part 2 – Scope – Pointers and References – Dynamic Memory Allocation – Const-ness – Function Overloading • Part 3 – Type System – Brief Intro to Using Templates – C++ Data Structures – Standard Template Library Containers • Part 4 – Object Oriented Design – Classes in C++ 2 / 82 Typeface Conventions • Key concepts • Special attention required! • Code • // Comments • int x;// Language keywords 3 / 82 MOOSE Coding Standards • Capitalization –ClassName –methodName – member variable – local variable • FileNames – src/ClassName.C – include/ClassName.h • Spacing – Two spaces for each indentation level – Four spaces for initialization lists – Braces should occupy their own line – Spaces around all binary operators and declaration symbols + - * & ... • No Trailing Whitespace! • Documentation for each method (Doxygen keywords) – @param – @return – ///Doxygen Style Comment • See our wiki page for a comprehensive list https://hpcsc.inl.gov/moose/wiki/CodeStandards 4 / 82 Part 1 • Basic Syntax Review • C++ Definitions • Source Code Organization • Building your Code 5 / 82 Review: C Preprocessor Commands • “#” Should be the first character on the line – #include <iostream> – #include "myheader.h" – #define SOMEWORD value – #ifdef, #ifndef, #endif • Some predefined Macros – FILE – LINE – cplusplus 6 / 82 Review: Intrinsic Data Types Basic Type Variant(s) bool char unsigned int unsigned, long, short float double
    [Show full text]
  • Chapter 4 Methods
    Chapter 4 Methods Hello! Today we will focus on the static keyword, calling conventions of methods, and what scope and lifetime mean in Java. Now that our chapters will tend to generate multiple files, I strongly suggest you create a folder for each lab, and then just add files to that folder. Naming Things. Quick note on names: when we create a variable in a class – whether we make it static or not – we can refer to it as a field. We may refer to both fields and methods as members of the class. Although we have strived to use the same names for things, these words are commonly used to refer to the variables and methods in a class. Methods – Static Methods The way in Java to name a block of code, and then be able to call it elsewhere, is to write a method. A method always goes in a class definition. We have one major distinction to make, though: should the method be static or not? A static method can be called all by itself (no object of the enclosing class needed), much like a function in Python. A non-static method in Java is written in a class and associated with a particular object and thus can use the object's instance variables. Being non-static is the default behavior in Java, specified by the absence of the static modifier. We focus first in this tutorial on writing static methods. Non-static Method Example Here is an example of a non-static method, in the Square class: look at the perimeter method below.
    [Show full text]