This document discusses program development and outlines a lesson on object-oriented programming concepts. It covers the four basic activities of program development: establishing requirements, creating a design, implementing code, and testing. It then outlines topics to be covered in the lesson including method design, creating objects, loop statements, classes and objects, and more. Examples are provided of creating classes to represent dice and students. The use of for loops is demonstrated through examples printing weekdays, multiples of a number, and a triangle of asterisks.
This document discusses comparing data types in Java, including:
1) Floating point values should not be compared directly for equality due to precision issues, instead compare that the absolute difference is less than a small tolerance value.
2) Strings and characters can be compared lexicographically based on their ordering in Unicode character sets, or using the equals() and compareTo() methods.
3) Shorter strings come before longer strings with the same prefix, and uppercase letters come before lowercase letters.
1. The document discusses the anatomy of methods and classes in Java. It explains that a Java application consists of more than one class, with the starting class containing the main method. Other classes are used to encapsulate data and functionality.
2. It describes what a method declaration is and how method control flow works. When a method is invoked, the flow jumps to the method code and returns after completion. Methods can return values.
3. The document also covers instantiating classes to create objects. Instance methods require object creation using the new operator before being called. Instance variables store data in objects and are available throughout the class.
This document provides an outline and examples for creating objects in Java. It discusses creating object instances from classes, using constructors to initialize objects, and defining instance variables and methods. The document uses a bank account example to demonstrate how to:
- Define an Account class with fields for account number, balance, and name
- Create Account objects by calling the constructor
- Add methods like deposit(), withdraw(), and transfer() that update the object's balance field
- Create multiple Account objects to represent different bank accounts
- Use input methods and output statements when calling object methods
The document provides an overview of Lesson 3 which will address random and math classes, conditional statements including if, if-else, and switch statements. It discusses variables, data types, operators, and methods from classes like Random, Math, and Scanner. The document also covers formatting output, indentation, block statements, nested if statements, and the logic of if and if-else statements.
JavaScript is an object-oriented scripting language used to make webpages interactive. It can access and modify the content, structure, and style of an HTML document. JavaScript code can be embedded directly in HTML, or linked from external .js files. The Document Object Model (DOM) represents an HTML document as nodes that JavaScript can manipulate by accessing properties and methods. Functions are blocks of JavaScript code that perform tasks when called.
The static keyword in Java is used for memory management and can be applied to variables, methods, blocks, and nested classes. Static variables and methods belong to the class rather than objects. A static variable is loaded when the class is loaded and there is only one copy per class, while instance variables are loaded each time an object is created. The main method must be static since it is called before any objects are created to start the program execution. Static blocks are used to initialize static variables and are executed when the class is loaded.
The static keyword in Java is used for memory management. It allows variables and methods to belong to the class rather than instances of the class. Static variables and methods are associated with the class, not objects, so they can be accessed without creating an object of the class. Static variables only have one copy in memory and static methods can access static variables and change their values without creating an object. Examples demonstrate how to declare static variables and methods and how they differ from non-static variables and methods.
The document discusses the static keyword in Java. It explains that static members belong to the class rather than objects, and are loaded when the class is loaded. Static variables and methods can be accessed without creating an object. Constructors are used to initialize non-static variables when an object is created. Static blocks run when the class is loaded and can initialize static variables.
This document discusses comparing data types in Java, including:
1) Floating point values should not be compared directly for equality due to precision issues, instead compare that the absolute difference is less than a small tolerance value.
2) Strings and characters can be compared lexicographically based on their ordering in Unicode character sets, or using the equals() and compareTo() methods.
3) Shorter strings come before longer strings with the same prefix, and uppercase letters come before lowercase letters.
1. The document discusses the anatomy of methods and classes in Java. It explains that a Java application consists of more than one class, with the starting class containing the main method. Other classes are used to encapsulate data and functionality.
2. It describes what a method declaration is and how method control flow works. When a method is invoked, the flow jumps to the method code and returns after completion. Methods can return values.
3. The document also covers instantiating classes to create objects. Instance methods require object creation using the new operator before being called. Instance variables store data in objects and are available throughout the class.
This document provides an outline and examples for creating objects in Java. It discusses creating object instances from classes, using constructors to initialize objects, and defining instance variables and methods. The document uses a bank account example to demonstrate how to:
- Define an Account class with fields for account number, balance, and name
- Create Account objects by calling the constructor
- Add methods like deposit(), withdraw(), and transfer() that update the object's balance field
- Create multiple Account objects to represent different bank accounts
- Use input methods and output statements when calling object methods
The document provides an overview of Lesson 3 which will address random and math classes, conditional statements including if, if-else, and switch statements. It discusses variables, data types, operators, and methods from classes like Random, Math, and Scanner. The document also covers formatting output, indentation, block statements, nested if statements, and the logic of if and if-else statements.
JavaScript is an object-oriented scripting language used to make webpages interactive. It can access and modify the content, structure, and style of an HTML document. JavaScript code can be embedded directly in HTML, or linked from external .js files. The Document Object Model (DOM) represents an HTML document as nodes that JavaScript can manipulate by accessing properties and methods. Functions are blocks of JavaScript code that perform tasks when called.
The static keyword in Java is used for memory management and can be applied to variables, methods, blocks, and nested classes. Static variables and methods belong to the class rather than objects. A static variable is loaded when the class is loaded and there is only one copy per class, while instance variables are loaded each time an object is created. The main method must be static since it is called before any objects are created to start the program execution. Static blocks are used to initialize static variables and are executed when the class is loaded.
The static keyword in Java is used for memory management. It allows variables and methods to belong to the class rather than instances of the class. Static variables and methods are associated with the class, not objects, so they can be accessed without creating an object of the class. Static variables only have one copy in memory and static methods can access static variables and change their values without creating an object. Examples demonstrate how to declare static variables and methods and how they differ from non-static variables and methods.
The document discusses the static keyword in Java. It explains that static members belong to the class rather than objects, and are loaded when the class is loaded. Static variables and methods can be accessed without creating an object. Constructors are used to initialize non-static variables when an object is created. Static blocks run when the class is loaded and can initialize static variables.
Static member functions can be accessed without creating an object of the class. They are used to access static data members, which are shared by all objects of a class rather than each object having its own copy. The examples show declaring a static data member n and static member function show() that prints n. show() is called through the class name without an object. Each object creation in the constructor increments n, and show() prints the updated count.
Software Engineering :UML class diagramsAjit Nayak
The document discusses UML class diagrams and their components. It defines a class diagram as representing entities with common features as rectangles divided into compartments for the class name, attributes, and operations. It provides examples of how different relationships like association, aggregation, and generalization are depicted. Key points include that association represents a "has-a" relationship, aggregation a whole-part relationship where parts can exist independently, and generalization an "is-a" relationship of inheritance.
This chapter discusses software engineering principles and object-oriented programming concepts in Java. It covers the software development life cycle, algorithm analysis using Big-O notation, defining and using classes and objects in Java, UML class diagrams, constructors and destructors, and abstract data types. The chapter also provides an example programming problem on modeling a candy machine using object-oriented design principles.
This document provides an introduction to Java programming basics. It discusses that Java is an object-oriented programming language that uses classes and objects. The basic building block of a Java program is the class, which can contain variables and methods. An executable Java program must have a main method, which is the entry point of the program. The document then covers Java data types, control structures like if-else and loops, working with strings and math functions. It also demonstrates how to pass command line arguments to a Java program.
This document discusses data members and member functions in C++ classes. It defines data members as variables declared inside a class that can be of any type. Member functions are functions declared inside a class that can access and perform operations on the class's data members. The document outlines how data members and member functions can be defined with public, private, or protected visibility and how they can be accessed from within and outside the class. It also provides syntax examples for defining member functions both inside and outside the class definition.
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...Wagdy Mohamed
This document provides an overview of arrays, functions, and object-oriented programming concepts in 3 sections. The arrays section covers 1D and 2D arrays, static vs dynamic arrays, and examples of declaring and initializing arrays. The functions section defines function headers, bodies, access specifiers, return types, parameters. The introduction to OOP section defines classes, objects, setters and getters, constructors, and provides examples of creating a class and object.
The document discusses static data members in C++. It explains that a static data member is shared among all objects of a class and is defined with the static keyword. Only one variable is created in memory even if there are multiple objects. It is visible only within the class and persists for the lifetime of the program. The document provides examples of declaring and defining static data members separately, and using them to assign unique roll numbers to student objects.
The document discusses key concepts of object-oriented programming using C++ including defining classes, encapsulation, static vs non-static members, and polymorphism. A class defines a category of objects by grouping related data and functions. Classes encapsulate data by hiding implementation details and exposing an interface. Static members are shared across all objects while non-static members are unique to each object instance. Polymorphism allows the same operation to behave differently based on the object type.
This document provides information about the CS3101-3 Programming Language - JAVA course for Fall 2004. It introduces the instructor, Ke Wang, and his contact information. It states the class will meet on Wednesdays from 11am-1pm for 6 weeks ending on October 20th. There will be 5-6 homework assignments due on Tuesdays at 11:59:59pm. Late submissions are allowed once with a 24-hour extension. The document outlines topics that will be covered in the course like Java basics, objects, classes, inheritance, and GUI programming. It provides references to online textbooks and tutorials that can be used. Finally, it encourages students to practice programming to learn the language.
This document provides information about the CS3101-3 Programming Language - JAVA course for Fall 2004. It introduces the instructor, Ke Wang, and his contact information. It states the class will meet on Wednesdays from 11am-1pm for 6 weeks ending on October 20th. There will be 5-6 homework assignments due on Tuesdays at 11:59:59pm. Late submissions are allowed once with a 24-hour extension. The document outlines topics that will be covered in the course like Java basics, objects, classes, inheritance, and GUI programming. It provides references to online textbooks and tutorials that can be used. Finally, it encourages students to practice programming to learn the language.
Refinement types are an approach for expressing more detailed properties of data types using propositional logic predicates. Liquid Haskell is a static refinement type checker capable of veryfing refinement type safety. We will examine the possibilites this approach opens for increasing development productivity.
Objects represent real-world entities and have unique identities, states, and behaviors. A class defines the structure and behavior of objects through instance variables and methods. Objects are created from classes and inherit their structure and functionality. Key concepts in object-oriented programming include encapsulation, polymorphism, inheritance, abstract classes, and static and dynamic binding.
The document discusses classes and objects in object-oriented programming. It defines a class as a blueprint that defines the data and functions that objects of that class will have. Objects are instances of a class that reserve memory and can access class data members and methods. The document outlines how to define a class with public and private sections, and how to then define objects as instances of a class that can access class methods.
This document compares the functional programming languages Haskell and Scala. It outlines their similarities such as being high-level, statically typed, and supporting functions as first-class values. It describes some of their conceptual differences like Haskell emphasizing purity and lazy evaluation while Scala allows side effects. It then provides examples to illustrate extra features of each language, such as Haskell's pointfree style and compiler extensions, and Scala's support for object-oriented and imperative programming. Finally, it discusses some practical considerations for using each language.
The final keyword in Java can be applied to variables, methods, and classes. It restricts changes to final entities. Final variables must be initialized after declaration and their values cannot be changed. Final methods cannot be overridden in subclasses. Final classes cannot be subclassed. Blank final variables are not initialized in their declaration and can only be initialized in a constructor or static block.
The document discusses classes and methods in Java. It defines that a class is a user-defined data type that serves as a template to define properties. A class contains fields to store data and methods to perform actions. Methods are declared inside the class and can access and modify the class fields. The document also discusses creating objects from classes using the new keyword, using constructors to initialize objects, using this keyword to refer to class fields from methods, method overloading and static methods.
Abstract: This PDSG workshop introduces basic concepts of categorical variables in training data. Concepts covered are dummy variable conversion, and dummy variable trap.
Level: Fundamental
Requirements: No prior programming or statistics knowledge required.
An abstract class is a base class that is meant to be inherited from but cannot be instantiated. It may contain implemented and unimplemented members, with unimplemented members denoted as abstract. Derived classes must implement all abstract members. An interface defines a contract that classes can implement but contains no implementation. Classes implementing an interface must provide method bodies for all interface members. Interfaces can inherit other interfaces.
A key contribution for leveraging trustful interactionsSónia
This document discusses human-computer trust from both an HCI and trust perspective. It examines trust as a crucial element in human relationships and represents value-centered interactions between humans and computers. The research aims to identify the social values and qualities that underlie people's trust beliefs and how those trustworthy qualities are represented with technology becoming more ubiquitous. Through literature reviews and participatory design sessions, the research models trust as a social phenomenon and validates how trust relates to users' activities. It identifies factors like honesty, reliability, and predictability that influence users' attitudes around sharing, relating, and communicating. The results are used to develop a model of human-computer trust and a design space toolset to assess and evaluate trust-en
1) O documento discute como cultivar interações com confiança em sistemas interativos, analisando o conceito de confiança e propondo um modelo sociotécnico de confiança.
2) O modelo identifica indicadores como expectativas, percepção racional e emocional que influenciam a predisposição para confiar e cooperar.
3) Também aborda desafios no desenvolvimento de software interativo para cultivar confiança, propondo abordagens interdisciplinares que considerem tanto aspectos técnicos como sociais.
This document provides an overview of CSS3 transitions and animations for front-end web development. It discusses how to use CSS3 transitions to gradually change styles between elements without JavaScript. It also covers how to create animations in CSS3 using @keyframes to control steps and binding animations to selectors using properties like animation-duration. Examples are provided to demonstrate transitions and animations. The document concludes with information on using Animate.css for easy CSS3 animations and assigning a lab for teams to work on an Egg Drop game.
Static member functions can be accessed without creating an object of the class. They are used to access static data members, which are shared by all objects of a class rather than each object having its own copy. The examples show declaring a static data member n and static member function show() that prints n. show() is called through the class name without an object. Each object creation in the constructor increments n, and show() prints the updated count.
Software Engineering :UML class diagramsAjit Nayak
The document discusses UML class diagrams and their components. It defines a class diagram as representing entities with common features as rectangles divided into compartments for the class name, attributes, and operations. It provides examples of how different relationships like association, aggregation, and generalization are depicted. Key points include that association represents a "has-a" relationship, aggregation a whole-part relationship where parts can exist independently, and generalization an "is-a" relationship of inheritance.
This chapter discusses software engineering principles and object-oriented programming concepts in Java. It covers the software development life cycle, algorithm analysis using Big-O notation, defining and using classes and objects in Java, UML class diagrams, constructors and destructors, and abstract data types. The chapter also provides an example programming problem on modeling a candy machine using object-oriented design principles.
This document provides an introduction to Java programming basics. It discusses that Java is an object-oriented programming language that uses classes and objects. The basic building block of a Java program is the class, which can contain variables and methods. An executable Java program must have a main method, which is the entry point of the program. The document then covers Java data types, control structures like if-else and loops, working with strings and math functions. It also demonstrates how to pass command line arguments to a Java program.
This document discusses data members and member functions in C++ classes. It defines data members as variables declared inside a class that can be of any type. Member functions are functions declared inside a class that can access and perform operations on the class's data members. The document outlines how data members and member functions can be defined with public, private, or protected visibility and how they can be accessed from within and outside the class. It also provides syntax examples for defining member functions both inside and outside the class definition.
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...Wagdy Mohamed
This document provides an overview of arrays, functions, and object-oriented programming concepts in 3 sections. The arrays section covers 1D and 2D arrays, static vs dynamic arrays, and examples of declaring and initializing arrays. The functions section defines function headers, bodies, access specifiers, return types, parameters. The introduction to OOP section defines classes, objects, setters and getters, constructors, and provides examples of creating a class and object.
The document discusses static data members in C++. It explains that a static data member is shared among all objects of a class and is defined with the static keyword. Only one variable is created in memory even if there are multiple objects. It is visible only within the class and persists for the lifetime of the program. The document provides examples of declaring and defining static data members separately, and using them to assign unique roll numbers to student objects.
The document discusses key concepts of object-oriented programming using C++ including defining classes, encapsulation, static vs non-static members, and polymorphism. A class defines a category of objects by grouping related data and functions. Classes encapsulate data by hiding implementation details and exposing an interface. Static members are shared across all objects while non-static members are unique to each object instance. Polymorphism allows the same operation to behave differently based on the object type.
This document provides information about the CS3101-3 Programming Language - JAVA course for Fall 2004. It introduces the instructor, Ke Wang, and his contact information. It states the class will meet on Wednesdays from 11am-1pm for 6 weeks ending on October 20th. There will be 5-6 homework assignments due on Tuesdays at 11:59:59pm. Late submissions are allowed once with a 24-hour extension. The document outlines topics that will be covered in the course like Java basics, objects, classes, inheritance, and GUI programming. It provides references to online textbooks and tutorials that can be used. Finally, it encourages students to practice programming to learn the language.
This document provides information about the CS3101-3 Programming Language - JAVA course for Fall 2004. It introduces the instructor, Ke Wang, and his contact information. It states the class will meet on Wednesdays from 11am-1pm for 6 weeks ending on October 20th. There will be 5-6 homework assignments due on Tuesdays at 11:59:59pm. Late submissions are allowed once with a 24-hour extension. The document outlines topics that will be covered in the course like Java basics, objects, classes, inheritance, and GUI programming. It provides references to online textbooks and tutorials that can be used. Finally, it encourages students to practice programming to learn the language.
Refinement types are an approach for expressing more detailed properties of data types using propositional logic predicates. Liquid Haskell is a static refinement type checker capable of veryfing refinement type safety. We will examine the possibilites this approach opens for increasing development productivity.
Objects represent real-world entities and have unique identities, states, and behaviors. A class defines the structure and behavior of objects through instance variables and methods. Objects are created from classes and inherit their structure and functionality. Key concepts in object-oriented programming include encapsulation, polymorphism, inheritance, abstract classes, and static and dynamic binding.
The document discusses classes and objects in object-oriented programming. It defines a class as a blueprint that defines the data and functions that objects of that class will have. Objects are instances of a class that reserve memory and can access class data members and methods. The document outlines how to define a class with public and private sections, and how to then define objects as instances of a class that can access class methods.
This document compares the functional programming languages Haskell and Scala. It outlines their similarities such as being high-level, statically typed, and supporting functions as first-class values. It describes some of their conceptual differences like Haskell emphasizing purity and lazy evaluation while Scala allows side effects. It then provides examples to illustrate extra features of each language, such as Haskell's pointfree style and compiler extensions, and Scala's support for object-oriented and imperative programming. Finally, it discusses some practical considerations for using each language.
The final keyword in Java can be applied to variables, methods, and classes. It restricts changes to final entities. Final variables must be initialized after declaration and their values cannot be changed. Final methods cannot be overridden in subclasses. Final classes cannot be subclassed. Blank final variables are not initialized in their declaration and can only be initialized in a constructor or static block.
The document discusses classes and methods in Java. It defines that a class is a user-defined data type that serves as a template to define properties. A class contains fields to store data and methods to perform actions. Methods are declared inside the class and can access and modify the class fields. The document also discusses creating objects from classes using the new keyword, using constructors to initialize objects, using this keyword to refer to class fields from methods, method overloading and static methods.
Abstract: This PDSG workshop introduces basic concepts of categorical variables in training data. Concepts covered are dummy variable conversion, and dummy variable trap.
Level: Fundamental
Requirements: No prior programming or statistics knowledge required.
An abstract class is a base class that is meant to be inherited from but cannot be instantiated. It may contain implemented and unimplemented members, with unimplemented members denoted as abstract. Derived classes must implement all abstract members. An interface defines a contract that classes can implement but contains no implementation. Classes implementing an interface must provide method bodies for all interface members. Interfaces can inherit other interfaces.
A key contribution for leveraging trustful interactionsSónia
This document discusses human-computer trust from both an HCI and trust perspective. It examines trust as a crucial element in human relationships and represents value-centered interactions between humans and computers. The research aims to identify the social values and qualities that underlie people's trust beliefs and how those trustworthy qualities are represented with technology becoming more ubiquitous. Through literature reviews and participatory design sessions, the research models trust as a social phenomenon and validates how trust relates to users' activities. It identifies factors like honesty, reliability, and predictability that influence users' attitudes around sharing, relating, and communicating. The results are used to develop a model of human-computer trust and a design space toolset to assess and evaluate trust-en
1) O documento discute como cultivar interações com confiança em sistemas interativos, analisando o conceito de confiança e propondo um modelo sociotécnico de confiança.
2) O modelo identifica indicadores como expectativas, percepção racional e emocional que influenciam a predisposição para confiar e cooperar.
3) Também aborda desafios no desenvolvimento de software interativo para cultivar confiança, propondo abordagens interdisciplinares que considerem tanto aspectos técnicos como sociais.
This document provides an overview of CSS3 transitions and animations for front-end web development. It discusses how to use CSS3 transitions to gradually change styles between elements without JavaScript. It also covers how to create animations in CSS3 using @keyframes to control steps and binding animations to selectors using properties like animation-duration. Examples are provided to demonstrate transitions and animations. The document concludes with information on using Animate.css for easy CSS3 animations and assigning a lab for teams to work on an Egg Drop game.
This document provides an overview of HTML (Hypertext Markup Language) including basic concepts, elements, and structure. It discusses HTML as a markup language interpreted by web browsers to define the structure of web pages and present content. The key elements covered include text formatting, lists, hyperlinks, images, tables, and forms. It also discusses HTML5 additions and differences between HTML and XHTML.
This document outlines a presentation on conceptualizing trust within human-computer interaction. It discusses:
1) Moving beyond trust "in" technologies to an "existential trust" of one's ability to understand themselves and interact with a computerized world.
2) How ubiquitous computing pervades our lives and influences how we experience and think about our relationships with technology.
3) The concept of "reflective HCI" design that focuses on openness, engagement, and interpretation to address aesthetic and excessive forms of technological risk people experience.
The presentation argues for considering how technology design can influence users' sense of self and support voicing subjective concerns, rather than just making technologies efficient and transparent.
This document discusses responsive web design. It defines responsive design as designs that can adjust to different screen sizes and devices. It distinguishes between fixed, fluid, and responsive layout types. Fixed layouts have a set pixel width and do not adjust to different screens. Fluid layouts use percentages for widths to adjust to the browser window size. Responsive designs use both fixed and fluid elements along with media queries to dynamically adjust the layout. The document provides guidelines for implementing each type of layout and discusses using grids to create flexible and adaptive designs.
Literature, Law and Learning: Excursions from Computer ScienceClare Hooper
The slides I presented at Interdisciplinary Coups and Calamities 2014 about my accepted paper. The abstract of the paper follows:
With the goal of identifying success factors for interdisciplinary collaboration, this paper describes three such collaborations by a computer scientist with: a digital culture researcher from a literary background; an IT law professor; and an education specialist with a background in modern languages. Success factors are discussed for each collaboration and four success factors are suggested: established shared context; strong communication; closeness of relationship between disciplines; typology of collaboration.
The document provides an overview of Cascading Style Sheets (CSS). CSS allows you to create rules that control the presentation of HTML elements. CSS syntax includes selectors that point to HTML elements and declaration blocks that contain properties and values to style those elements. There are different ways to insert CSS into HTML documents, including external style sheets, internal style sheets, and inline styles. CSS uses the box model to style elements, which includes properties for dimensions, padding, borders, and margins.
Trust from a Human Computer Interaction perspective Sónia
Persuasion, Emotion and Trust (PET) is a design methodology that enables design more technologically engaging products. PET uses three main design values,
Persuasion – Triggers actions;
Emotion - Generate an emotional response; and
Trust – Leveraging credibility and cooperation.
This design methodology main aim is to incentives people to become more engaged and connected with a certain product or ecosystems.
Our main aim is to stress the role of trust on persuasive design.
In general, we will focus on the following aspects:
1) First we will start by creating a clear understanding on the challenges of transferring Human Computer Trust (HCT) values to influence user engagement and fostering trust-enabling interactions.
2) Then, in the second part we will learn to analyze interaction design sequences from digital products that changes human trust behaviors. As well as explore different methodologies for testing.
3) We will end by presenting and reflection on the result achieved.
For more information read my human computer trust blog https://humancomputertrust.wordpress.com
Helping users in assessing the trustworthiness of user-generated reviewsThe Research Thing
This document summarizes research on how interface design can help users distinguish between trustworthy and untrustworthy online reviews. A user study examined how interface elements like the number of reviews, helpful votes, and city/country listings impacted assessments of review quality, source expertise, and bias. Results showed users relied more on reviews with more helpful votes and reviews from sources with more total reviews to judge trustworthiness. The study also found high dispositional trust users and low dispositional trust users relied on interface elements differently. The document concludes interface design should provide more direct signals of source bias, evidence of accuracy, and transparency about online community opinions to help users assess review trustworthiness.
Technology in general -- and the internet and social media specifically -- have changed the way we work. And not just by shifting the mediums through which we communicate, but by changing the very nature of what we communicate. Technology is blurring the line between our personal and professional selves and changing our expectations of each other and our organizations.
Each nonprofit’s story is more than a mission statement, a website or an annual report. The story also includes the people inside and those on the front lines. It's how individuals represent the mission statement and organizational values that bring the vision to life online and out in the world. Blending individual and organizational stories is crucial to success in the digital age.
So, how can organizations and individuals work together to do this?
Nancy Lyons and Meghan Wilker of the Geek Girls Guide will speak about the intersection of technology and humanity, and the role of individuals in representing an organization.
The document discusses building interactive systems using Xcode and Swift. It introduces key programming concepts like object-oriented programming, variables and types, functions, conditionals, and Xcode components like the interface builder, simulator, and assistant editor. It explains how to create a basic Xcode project with labels, connect the labels to code using outlets, and set label text in the viewDidLoad function. The document provides an overview of building blocks for programming interactive apps in Xcode.
Technology Trust 08 24 09 Power Point Finaljhustad1
Technology Trust provides resources and support for development stage life science companies. They have extensive experience developing life science companies from inception through commercialization. Their process involves vetting technologies, performing due diligence, helping companies prepare presentations for investors, and introducing companies to their network of venture capital and angel investors with the goal of securing necessary financing. They have a team of associates with expertise in areas important to life science companies such as product research, clinical strategy, manufacturing, legal, accounting, and more.
This document discusses Edward De Bono's 6 Thinking Hats method for group discussions. It provides examples of how each "hat" or perspective could be applied when considering opening a new restaurant: the White Hat focuses on objective facts, the Yellow Hat on optimism, the Green Hat on creative ideas, the Black Hat on criticism, the Red Hat on emotions, and the Blue Hat on process and agenda. The document encourages using a maximum of 2 hats per person during a discussion and avoiding overuse of the Black Hat. It also provides guidance on using this technique for a workshop on evaluating concepts.
A design space for Trust-enabling Interaction DesignSónia
This document discusses trust-enabling interaction design from multiple perspectives. It examines trust from HCI, social, and technical views. Key points discussed include:
- Trust is a key element in human relationships and enables more decisive actions and smooth activities.
- A multidiciplinary approach is needed as trust has been studied in fields like sociology, political science, economics, and more.
- In human-computer interactions, trust is important and qualities like honesty, predictability, and benevolence can help enable trust.
- A proposed model examines factors that influence user trust predisposition and systems' trustworthiness. Designing for qualities like enabling honest behavior and facilitating prediction of others can help foster social engagement
This document discusses user experience evaluation. It explains that evaluation is needed to understand user needs, identify design issues, and improve the user experience. Different evaluation methods are appropriate at different stages of development, including early concept testing, low-fidelity prototyping, and high-fidelity testing. A variety of methods can provide both qualitative and quantitative data, including usability testing, surveys, interviews, and analytical metrics. Properly selecting evaluation techniques and planning the procedure is important to obtain high-quality feedback for optimizing the user experience.
Technology and Trust: The Challenge of 21st Century GovernmentTim O'Reilly
The document summarizes Tim O'Reilly's talk on how technology and trust in government are linked. He argues that while technology has revolutionized many industries, government has been slow to adopt these changes. This has led to a decline in public trust as government services fail to meet citizens' expectations set by their digital experiences elsewhere. O'Reilly cites the UK's Government Digital Service as a positive example of an agency that has successfully modernized government websites and digital services through an iterative process focused on user needs rather than bureaucratic requirements.
Trust in IT: Factors, Metrics and ModelsClare Hooper
The TRIFoRM project brought together computer science, health science, social science and engineering to explore the trusting beliefs of users of IT systems, looking at factors that influence trust of systems and ways to model those factors and trust levels. The team focused particularly on healthcare technologies for monitoring chronic conditions, and interviewed people who may use or provide healthcare monitoring technology to understand what was important to them as individuals. Analysis of the interviews let the team identify possible threats to trust of technology, and controls to mitigate those threats. In addition, the team identified two key issues. The first issue was that it is clear that people using a monitoring technology to manage pain are more likely to take risks and tolerate faults, making them more vulnerable. The second issue is the importance of relationships: patients were concerned that monitoring technology might change their relationship with healthcare providers, as well as with whether healthcare providers themselves trust the technology.
Clare Hooper is a computer scientist specialised in human-computer interaction, user experience and web science. She has led various national research projects in the UK as well as major work packages in EU projects. Clare enjoys the challenges and rewards of interdisciplinary work, and has recently moved to Vancouver.
An Operating System for the Real WorldTim O'Reilly
My keynote at the Concur #PerfectTrip Devcon on October 2, 2013. I talk about the "internet operating system," and how sensors are turning it into a real world operating system, with "context aware programming." I use this metaphor to give lessons from some projects and startups putting these principles to work, including Tripit, the Google Autonomous Vehicle, Square, Uber, and Google Now.
This document provides an introduction and overview of Java programming concepts including:
- Java can be used to create dynamic web applications, native applications, and is not the same as JavaScript.
- The basic structure of a Java program includes object-oriented concepts like classes, objects, inheritance. Development environments like Eclipse help facilitate Java development.
- Variables represent object state and methods represent object behavior. Classes are templates that define common attributes and behaviors of objects.
- Eclipse is an integrated development environment used for Java development which allows editing, compiling and running Java programs.
This document discusses static data members in C++. It explains that a static data member is shared among all objects of a class and is defined with the static keyword. Only one variable is created in memory even if there are multiple class objects. It is visible only within the class and persists for the lifetime of the program. The document provides examples of declaring and defining static data members separately, and using a static member to assign unique roll numbers to student objects.
The document discusses a lecture on object-oriented programming. It covers key topics like classes, objects, fields, methods, constructors, and creating objects from classes. It provides examples of how to define classes with fields, methods, and constructors. It also explains how to compile and run a simple Java program with a main method.
This document provides an overview of object-oriented programming concepts including classes, objects, encapsulation and abstraction. It begins by describing the objectives of learning OOP which are to describe objects and classes, define classes, construct objects using constructors, access object members using dot notation, and apply abstraction and encapsulation. It then compares procedural and object-oriented programming, noting that OOP involves programming using objects defined by classes. Key concepts covered include an object's state consisting of data fields and behavior defined by methods. The document demonstrates defining classes, creating objects, accessing object members, and using private data fields for encapsulation.
The document discusses pointers and virtual functions in C++. It explains pointer to derived classes and static and dynamic binding. Pointer to derived classes allows a pointer of a base class to point to objects of derived classes. Static binding occurs at compile time based on the static type of an object, while dynamic binding occurs at runtime based on the dynamic type of an object using virtual functions. The document provides examples of static and dynamic binding using an account class hierarchy. It also discusses upcasting, virtual function rules, and how dynamic binding works under the hood using virtual tables.
The document discusses classes and objects in C++. It defines classes as the building blocks of object-oriented programming that simplify development of large projects by producing software that is modular, reusable, and easily expandable. Classes are similar to structures but members of a class are private by default. The document then covers specifying a class, creating objects, accessing object members, static members, arrays of objects, objects as function arguments, returning objects, the this pointer, constant member functions, and more concepts related to classes in C++.
The document discusses classes, objects, and methods in Java. It defines a class as a template or blueprint from which objects are created. An object is an instance of a class that has state, behavior, and identity. It provides examples of defining a class with instance variables and methods, and creating objects of that class by allocating memory using the new operator. The document also discusses accessing object properties through reference variables and initializing objects by passing arguments to methods.
The document provides an introduction to object oriented programming (OOP) by comparing it to procedural programming. It discusses that OOP treats data as a critical element and ties data more closely to functions that operate on it. It allows decomposition of problems into objects that contain both data and functions. The four main pillars of OOP are discussed as objects, classes, encapsulation, and inheritance. Classes are defined as collections of similar objects that define attributes and behaviors of objects. Constructors and different types of constructors like parameterized and copy constructors are also introduced.
This document provides an introduction to object-oriented programming concepts in Java including objects, classes, inheritance, polymorphism, and more. It defines key terms like class, object, state, behavior, identity. It also discusses the differences between objects and classes and provides examples of declaring classes and creating objects in Java. Methods, constructors, and initialization of objects are explained. Inheritance, method overriding, and polymorphism are defined along with examples.
Class is a blueprint for creating objects that share common attributes and behaviors. A class defines the data and methods that describe the object. Classes in Java can contain data members, methods, constructors, nested classes, and interfaces. Objects are instances of classes that occupy memory at runtime and can access class members like variables and methods. Constructors initialize an object when it is created and have the same name as the class. The this keyword refers to the current object in a method or constructor. Command line arguments can be passed to a program as strings and accessed via the args parameter in the main method.
Class is a blueprint for creating object instances that share common attributes and behaviors. It defines the variables and methods that are common to all objects of that class. When an object is created from a class, it is said to be an instance of that class. Objects contain state in the form of attributes and behavior in the form of methods. Classes in Java can define access levels for variables and methods as public, private, protected, or without a specified level (default).
This document provides an overview of object-oriented programming (OOP) concepts in Java. It defines OOP as a style of programming that focuses on using objects to design and build applications. It describes what objects are, how they model real-world things, and how they use variables to store state and methods to define behavior. It then defines key OOP concepts like classes, objects, abstraction, encapsulation, polymorphism, method overriding, inheritance, and interfaces. For each concept, it provides a definition and example in Java code. The document is intended to help the reader learn more about these fundamental OOP concepts in Java.
This 5-day Java workshop covers object-oriented programming (OOP) concepts like encapsulation, abstraction, inheritance, and polymorphism. It discusses the four principles of OOP and how to achieve abstraction through classes, objects, and inheritance. The document provides examples of using objects, constructors, and the this keyword. It also covers access modifiers, static methods, and encapsulation to control access to object attributes through getters and setters.
This document provides a review of object-oriented programming concepts in Java, including:
- The difference between primitives and objects, and value vs reference semantics.
- How classes act as blueprints for objects, defining their data and behavior.
- Key object-oriented principles like encapsulation, fields, methods, and constructors.
- How objects pass by reference when used as parameters or assigned.
- Comparing objects requires special methods rather than using ==.
This document discusses evaluating user experience. It explains that evaluation is important to understand the value of a product from the user's perspective, identify design issues, and better understand the user experience. Evaluation can happen at different stages of development with different types of participants and study methods. It is important to evaluate both before and during usage to understand snapshots of interaction as well as long-term experience. The document covers when, where, who, what, and how to evaluate user experience.
This document provides an overview and outline of a lesson on variables and types in Java. The key points covered include:
- Variables are names for locations in memory that hold values. Primitive data types include numerical, character, and boolean values. Complex objects are instances of classes.
- Variables are declared with a data type, name, and optional initial value. Primitive values can be output and converted between types through casting or automatic promotion.
- Expressions combine operators and operands to compute results. Operators have precedence that determines the order of evaluation. Assignment operators store the result of an expression into a variable.
- The lesson covers primitive data types, variables, expressions, output, conversion, and creating objects
The goal of the course is to bring particular computer and programming skills to the level required by the studies. To create opportunities for the development of Java-based applications. To introduce programming basis and object-oriented principles using Java programming language.
This course is about evaluating the User Experience. It main goal is to highlight the experiential, affective, meaningful and valuable aspects of human-computer interaction as a complement to pragmatic attributes such as utility, ease of use and efficiency of the system.
This document discusses key concepts from the Diffusion of Innovation theory, including:
- There are different types of adopters (innovators, early adopters, early majority, late majority, laggards) who adopt innovations at different rates.
- Factors like relative advantage, compatibility, complexity, trialability, and observability influence how quickly an innovation is adopted.
- The innovation adoption process involves knowledge, persuasion, decision, implementation, and confirmation stages.
- Communication channels, time, and the social system all impact the spread of new ideas through a population.
This document presents an overview of a lesson on the technology acceptance model (TAM). The objective is to introduce key concepts of TAM, have student groups design concept maps of TAM, and summarize. TAM is presented as attempting to understand technology acceptance in organizations. It includes four versions and draws from other models like the theory of reasoned action. The core idea is that two key factors, perceived usefulness and perceived ease of use, influence users' decisions about adopting technologies.
This document provides an overview of the Human Centered Computing course IFI7172. The course aims to understand how computer technologies impact and are impacted by society. It takes a multidisciplinary approach and focuses on human, social, and cultural aspects of technology. The course covers topics like sociotechnical systems, technology acceptance, and innovation diffusion through lectures, activities, discussions, and case studies. Students are assessed based on participation, readings, discussions, case studies, and a final presentation. The goal is to study how technologies affect humans and society using human-centered methodologies.
This document discusses human-computer trust from both an HCI and trust perspective. It examines trust as a crucial element in human relationships and represents value-centered interactions between humans and computers. The research aims to identify the social values and qualities that underlie people's trust beliefs and how those trustworthy qualities are represented with technology becoming more ubiquitous. Through literature reviews and participatory design sessions, the research models trust as a social phenomenon and validates how trust relates to users' activities. It identifies factors like honesty, reliability, and predictability that influence users' trust and willingness to cooperate. The resulting human-computer trust model shows how qualities, beliefs, intentions and attitudes contribute to relationships and commitments between humans and computers.
This document outlines plans for evaluating the user experience of a product. It discusses conducting studies to understand how users perceive a product by comparing desktop and mobile versions. The project involves forming work groups, choosing an evaluation target, planning procedures, identifying participants, selecting methods, implementing a study, and reporting results. Suggested evaluation areas include first impressions, value/perceptions, emotions/mood, and usability. Various data collection methods are presented, such as surveys, mouse tracking, video recording, and physiological sensors.
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sónia
The document discusses a socio-technical model of trust in online learning interactions. It aims to understand the role of trust in supporting online interactions. The research examines trust through an extensive literature review and concept mapping. A survey was conducted to validate a proposed trust model with five attributes: reciprocity, reliability, honesty, empathy, and shared values/interests. The results showed words associated with these attributes influence individuals' trust in social interactions, sharing information, and online communication. Future work involves designing tools to monitor and support the development of trust over time in online learning environments.
This document discusses different ways to analyze and present performance metrics like time-on-task, number of errors, and number of steps taken when evaluating usability. It recommends measuring time-on-task by setting time thresholds and calculating percentages above or below thresholds. For errors, it suggests organizing them by task and calculating averages. And for steps, it proposes identifying meaningful actions and calculating averages by task to see which tasks require more effort. The document also notes issues to consider like double counting and provides tips for collecting and interpreting the different metrics.
1) The document describes a user experience workshop that aims to evaluate how users experience online media players through usability testing and heuristic evaluation.
2) The workshop involves usability testing using a think-aloud protocol and task completion rates, as well as an exploration test from both the user and designer perspective.
3) Participants are given 5-10 tasks to complete within a usability test session while thinking aloud, and success rates are calculated to measure effectiveness.
How to Add Chatter in the odoo 17 ERP ModuleCeline George
In Odoo, the chatter is like a chat tool that helps you work together on records. You can leave notes and track things, making it easier to talk with your team and partners. Inside chatter, all communication history, activity, and changes will be displayed.
How to Make a Field Mandatory in Odoo 17Celine George
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
How to Setup Warehouse & Location in Odoo 17 InventoryCeline George
In this slide, we'll explore how to set up warehouses and locations in Odoo 17 Inventory. This will help us manage our stock effectively, track inventory levels, and streamline warehouse operations.
2. Lesson 7 - Outline
22015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
3. Program Development
• The creation of software involves four basic
activities:
– establishing the requirements
– creating a design
– implementing the code
– testing the implementation
• These activities are not strictly linear – they
overlap and interact
2015 @ Sonia Sousa 3
4. Requirements
• Software requirements specify the tasks that a
program must accomplish
– what to do, not how to do it
• Often an initial set of requirements is provided, but
they should be critiqued and expanded
• It is difficult to establish detailed, unambiguous,
and complete requirements
• Careful attention to the requirements can save
significant time and expense in the overall project
2015 @ Sonia Sousa 4
5. Design
• A software design specifies how a program will
accomplish its requirements
• A software design specifies how the solution can be
broken down into manageable pieces and what each
piece will do
• An object-oriented design determines which classes
and objects are needed, and specifies how they will
interact
• Low level design details include how individual
methods will accomplish their tasks
2015 @ Sonia Sousa 5
6. Implementation
• Implementation is the process of translating a
design into source code
• Novice programmers often think that writing code
is the heart of software development, but actually
it should be the least creative step
• Almost all important decisions are made during
requirements and design stages
• Implementation should focus on coding details,
including style guidelines and documentation
2015 @ Sonia Sousa 6
7. Testing
• Testing attempts to ensure that the program will
solve the intended problem under all the
constraints specified in the requirements
• A program should be thoroughly tested with the
goal of finding errors
• Debugging is the process of determining the
cause of a problem and fixing it
• We revisit the details of the testing process later in
this chapter
2015 @ Sonia Sousa 7
8. Lesson 7 - Outline
82015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
9. Anatomy of a Class
Creating Students objects
2015 @ Sonia Sousa 9
10. Classes (Student, StudentCompare)
• Write a class that compares the grades of two
students and tells who is the best
• Classes Student and main class StudentCompare
• The Student class contains two data
values
• a String name that represents the student's name
• an double grade that represents the student’s grade
– Write a Student constructor to set the name and
the initial grade
10@ Sonia Sousa2015
11. Creating Objects
• An object has:
– state (attributes)
– String name
– double grade
• descriptive characteristics
– behaviors (what he can
do)
– compareStudents
11
StudentCompare
Name
Grade
compareStudents
Student
@ Sonia Sousa2015
12. Data scope
• The scope of data is the area in a program
in which that data can be referenced
(used)
– Data declared at the class level can be
referenced by all methods in that class
– Data declared within a method can be used
only in that method
– Data declared within a method is called local
data
12@ Sonia Sousa2015
13. Instance Data
• A variable declared at the class level (such as name)
– is called class attribute or instance variable
• Each instance (object) has its own instance variable
– A class declares the type of the data, but it does not reserve
memory space for it
• Each time a Student object is created,
– a new name variable is created as well
• The objects of a class share the method definitions,
– but each object has its own data space
• That's the only way two objects can have different states
13@ Sonia Sousa2015
14. // Student.java Author: Sónia Sousa
// Demonstrates the creation and use of a user-defined class.
public class Student {
private String name;
private double grade;
public Student(String name, double grade) {
this.name = name;
this.grade = grade;
}
public static void compareStudents(Student st1, Student st2)
{
if (st1.grade > st2.grade)
{ System.out.print(st1.name +" is a better student");}
else
{
if (st2.grade > st1.grade)
{System.out.print(st2.name +" is a better student");}
else
{System.out.println(st1.name+ " and " + st2.name+ "
are on the same level");}
}
}
continue 14
2015 @ Sonia Sousa
15. package studentManager;
import java.util.Scanner;
public class StudentCompare {
public static void main(String[] args) {
Student st1, st2, st3;
String name;
double grade;
Scanner scan = new Scanner(System.in);
System.out.println("Insert the first name for Student
1");
name = scan.next();
System.out.println("Insert the grade for Student 1");
grade = scan.nextDouble();
st1 = new Student(name,grade);
System.out.println("Insert the first name for Student
2");
name = scan.next();
System.out.println("Insert the grade for Student 2");
grade = scan.nextDouble();
st2 = new Student(name,grade);
Student.compareStudents(st1, st2);
} 15@ Sonia Sousa
continue
2015
16. Instance Data
• We can depict the two Student objects
from the Student program as follows:
16
st1 Johnname
st2 Maryname
Each object maintains its own name variable, and
thus its own state
@ Sonia Sousa2015
17. Quick Check
• Why was the grade variable declared as
private in the Student class?
– By making it private, each Student object
controls its own data and allows it to be modified
only by the well-defined operations it provides.
17@ Sonia Sousa2015
18. Classes
• The values of the data define the state of an object
created from the class
• The functionality of the methods define the behaviors
of the object
• For our Die class, we might declare an integer called
faceValue that represents the current value
showing on the face
• One of the methods would “roll” the die by setting
faceValue to a random number between one and
six
@ Sonia Sousa 182015
19. Anatomy of a Class
Creating Die objects
2015 @ Sonia Sousa 19
20. Classes (Die,RollingDice)
• Write a class that creates two six-sided
Die objects, both with an initial face value
of one.
– Rolls both dice and returns the combined
result.
– Returns the current combined dice total.
– Returns the current value of the first die.
– Returns the current value of the second die.
20@ Sonia Sousa2015
21. Creating Objects
• An object has:
– state (attributes)
• constant MAX that represents the maximum face value
int MAX = 6
• integer faceValue that represents the current face value
int faceValue = 1
– behaviors (what he can do)
• Rolls the die and returns the result.
– The roll method uses the random method of the Math class to
determine a new face value
faceValue = (int) (Math.random() * MAX) + 1;
21@ Sonia Sousa2015
22. Constructors
• As mentioned previously, a constructor is
used to set up an object when it is initially
created
• A constructor has the same name as the
class
• The Die constructor is used to set the
initial face value of each new die object to
one
@ Sonia Sousa 222015
23. //Die.java Author: Sonia Sousa
//Represents one die (singular of dice) with faces showing values
//between 1 and 6.
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue = 1; // current value showing on the die
// Constructor: sets the initial face value.
public Die(int faceValue) {
this.faceValue = faceValue;
}
// Rolls the die and returns the result.
public int roll()
{
faceValue = (int) (Math.random() * MAX) + 1;
return faceValue;
}
}
continue
@ Sonia Sousa 232015
24. continue
public class RollingDice2 {
public static void main(String[] args) {
// Creates two six-sided Die objects, both with an initial
// face value of one.
int faceValue = 1;
Die die1 = new Die(faceValue);
Die die2 = new Die(faceValue);
System.out.println (die1.roll());
System.out.println (die2.roll());
System.out.println ("Total: " + (die1.roll() +
die2.roll()));
}
}
@ Sonia Sousa 242015
25. Instance Data
• We can depict the two Die objects from
the RollingDice program as follows:
die1 5faceValue
die2 2faceValue
Each object maintains its own faceValue
variable, and thus its own state
@ Sonia Sousa 252015
26. Quick Check
Where is instance data declared?
What is the scope of instance data?
What is local data?
At the class level.
It can be referenced in any method of the class.
Local data is declared within a method, and is
only accessible in that method.
@ Sonia Sousa 262015
27. Anatomy of a Class
Additional examples
2015 @ Sonia Sousa 27
28. Lesson 7 - Outline
282015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
29. The for Statement
• A for statement has the following syntax:
for ( initialization ; condition ; increment )
statement;
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
The increment portion is executed at
the end of each iteration
2015 @ Sonia Sousa 29
30. Logic of a for loop
statement
true
condition
evaluated
false
increment
initialization
2015 @ Sonia Sousa 30
31. The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
2015 @ Sonia Sousa 31
32. The for Statement
• The initialization section can be used to
declare a variable
for (int count=1; count <= 5; count++)
System.out.println (count);
• Like a while loop, the condition of a for
loop is tested prior to executing the loop
body
• Therefore, the body of a for loop will
execute zero or more times
2015 @ Sonia Sousa 32
33. The for Statement
• The increment section can perform any calculation:
for (int num=100; num > 0; num -= 5)
System.out.println (num);
• A for loop is well suited for executing statements a
specific number of times that can be calculated or
determined in advance
• See ForLoop.java
• See Multiples.java
• See Stars.java
@ Sonia Sousa2015 33
35. Main class (ForLoop) package (loop)
• Start by creating the object array
– with the days of the week
static private String[] weekDays= {"Monday", "Tuesday”,
"Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
– Then print the results using a for iterate over an
array
• For loop that iterate over an array to print the String[]
for (int i = 0; i < weekDays.length; i++) {
System.out.println(weekDays[i]);
}
for ( initialization ; condition ; increment )
statement;
2015 @ Sonia Sousa 35
36. // ForLoop.java Author: Sónia Sousa
package loops;
public class repeatedLoop {
static private String[] weekDays= {"Monday",
"Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"};
public static void main(String[] args) {
// Demonstrates the use of a For loop
for (int i = 0; i < weekDays.length; i++) {
System.out.println(weekDays[i]);
}
}
}
362015 @ Sonia Sousa
38. Main class (Multiples) package (loop)
• Create a java application that
– Prints multiples of a user-specified number up to a
user-specified limit.
• Start by
– Scan a positive number and the upper limit and
print them
• Do a for loop that
– Print a specific number of values per line of
output
2015 @ Sonia Sousa 38
39. //********************************************************************
// Multiples.java Author: Lewis/Loftus
//
// Demonstrates the use of a for loop.
//********************************************************************
import java.util.Scanner;
public class Multiples
{
//-----------------------------------------------------------------
// Prints multiples of a user-specified number up to a user-
// specified limit.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int PER_LINE = 5;
int value, limit, mult, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a positive value: ");
value = scan.nextInt();
continue
2015 @ Sonia Sousa 39
40. continue
System.out.print ("Enter an upper limit: ");
limit = scan.nextInt();
System.out.println ();
System.out.println ("The multiples of " + value + " between " +
value + " and " + limit + " (inclusive) are:");
for (mult = value; mult <= limit; mult += value)
{
System.out.print (mult + "t");
// Print a specific number of values per line of output
count++;
if (count % PER_LINE == 0)
System.out.println();
}
}
}
2015 @ Sonia Sousa 40
41. continue
System.out.print ("Enter an upper limit: ");
limit = scan.nextInt();
System.out.println ();
System.out.println ("The multiples of " + value + " between " +
value + " and " + limit + " (inclusive) are:");
for (mult = value; mult <= limit; mult += value)
{
System.out.print (mult + "t");
// Print a specific number of values per line of output
count++;
if (count % PER_LINE == 0)
System.out.println();
}
}
}
Sample Run
Enter a positive value: 7
Enter an upper limit: 400
The multiples of 7 between 7 and 400 (inclusive) are:
7 14 21 28 35
42 49 56 63 70
77 84 91 98 105
112 119 126 133 140
147 154 161 168 175
182 189 196 203 210
217 224 231 238 245
252 259 266 273 280
287 294 301 308 315
322 329 336 343 350
357 364 371 378 385
392 399
2015 @ Sonia Sousa 41
43. Main class (Stars) package (loop)
• Create a java application that
– Prints a triangle shape using asterisk (star)
characters.
• Start by
– Create and initialize MAX_ROWS variable to 10
• Do a for loop that
– Print a specific number of values per line of
output
2015 @ Sonia Sousa 43
44. //********************************************************************
// Stars.java Author: Lewis/Loftus
//
// Demonstrates the use of nested for loops.
//********************************************************************
public class Stars
{
//-----------------------------------------------------------------
// Prints a triangle shape using asterisk (star) characters.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++)
{
for (int star = 1; star <= row; star++)
System.out.print ("*");
System.out.println();
}
}
}
2015 @ Sonia Sousa 44
45. @ Sonia Sousa
//********************************************************************
// Stars.java Author: Lewis/Loftus
//
// Demonstrates the use of nested for loops.
//********************************************************************
public class Stars
{
//-----------------------------------------------------------------
// Prints a triangle shape using asterisk (star) characters.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++)
{
for (int star = 1; star <= row; star++)
System.out.print ("*");
System.out.println();
}
}
}
Output
*
**
***
****
*****
******
*******
********
*********
**********
2015 45
46. Quick Check
• Write a code fragment that rolls a die 100 times
and counts the number of times a 3 comes up.
Die die = new Die();
int count = 0;
for (int num=1; num <= 100; num++)
if (die.roll() == 3)
count++;
Sytem.out.println (count);
2015 @ Sonia Sousa 46
47. The for Statement
• Each expression in the header of a for loop
is optional
• If the initialization is left out, no initialization is
performed
• If the condition is left out, it is always
considered to be true, and therefore creates
an infinite loop
• If the increment is left out, no increment
operation is performed
2015 @ Sonia Sousa 47
48. Lesson 7 - Outline
482015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
49. Identifying Classes and Objects
• The core activity of object-oriented design is determining
– the classes and objects that will make up the solution
• Then identify
– Classes may be part of a class library,
– Which classes we can reused from a previous project,
– Or, the one’s that will be newly written.
• One way to identify potential classes is to
– identify the objects discussed in the requirements
• Objects are generally nouns, and
• The services that an object provides are generally verbs.
2015 @ Sonia Sousa 49
50. Identifying Classes and Objects
• A partial requirements document:
• Of course, not all nouns will correspond to a
class or object in the final solution
The user must be allowed to specify each product by
its primary characteristics, including its name and
product number. If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log. The
summary report of all transactions must be structured
as specified in section 7.A.
2015 @ Sonia Sousa 50
51. Identifying Classes and Objects
• Remember that a class represents a group
(classification) of objects with the same behaviors
• Generally, classes that represent objects should
– Be given names that are singular nouns
• Examples: Coin, Student, Message
– A class represents the concept of one such object
• We are free to instantiate as many of each object as needed
2015 @ Sonia Sousa 51
52. Identifying Classes and Objects
• Sometimes it is challenging to decide whether
something should be represented as a class
– For example, should an employee's address be
represented as a set of instance variables or as an
Address object
• The more you examine the problem and its details
the more clear these issues become
• When a class becomes too complex,
– it often should be decomposed into multiple smaller
classes to distribute the responsibilities
2015 @ Sonia Sousa 52
53. Identifying Classes and Objects
• We want to define classes with the proper amount
of detail
– For example, it may be unnecessary to create
separate classes for each type of appliance in a
house
• It may be sufficient to define a more general
Appliance class with appropriate instance data
• It all depends on the details of the problem being
solved
2015 @ Sonia Sousa 53
54. Identifying Classes and Objects
• Part of identifying the classes we need is the
process of assigning responsibilities to each class
• Every activity that a program must accomplish
must be represented by one or more methods in
one or more classes
• We generally use verbs for the names of methods
• In early stages it is not necessary to determine
every method of every class – begin with primary
responsibilities and evolve the design
2015 @ Sonia Sousa 54
55. Lesson 7 - Outline
552015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Wrapper Classes
Static Variables and Methods
Class Relationships
Extra
56. Enumerated Types
• An enumerated type declaration
– lists all possible values for a variable of that type
– The values are identifiers of your own choosing
• The following declaration creates an
enumerated type called Season
enum Season {winter, spring, summer, fall};
• Any number of values can be listed
2015 @ Sonia Sousa 56
57. Enumerated Types
• Once a type is defined,
– a variable of that type can be declared:
Season time;
• And it can be assigned a value:
time = Season.fall;
– The values are referenced through the name of the type
• Enumerated types are type-safe
– you cannot assign any value other than those listed
2015 @ Sonia Sousa 57
58. Ordinal Values
• Internally, each value of an enumerated type
is stored as an integer,
– called its ordinal value
• The first value in an enumerated type
– has an ordinal value of zero, the second one, and
so on
• However, you cannot assign a numeric value
to an enumerated type,
– even if it corresponds to a valid ordinal value
2015 @ Sonia Sousa 58
59. Enumerated Types
• The declaration of an enumerated type is a
special type of class, and
– each variable of that type is an object
– cone1.ordinal()
• The ordinal method returns the ordinal value of the
object
– cone1.name()
• The name method returns the name of the identifier
corresponding to the object's value
• See IceCream.java
2015 @ Sonia Sousa 59
64. Lesson 7 - Outline
642015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
Extra
65. Static Class Members
• Recall that a static method is one that can be
invoked through its class name
• For example, the methods of the Math class
are static:
result = Math.sqrt(25)
• Variables can be static as well
• Determining if a method or variable should be
static is an important design decision
2015 @ Sonia Sousa 65
66. The static Modifier
• We declare static methods and variables
using the static modifier
• It associates the method or variable with the
class rather than with an object of that class
• Static methods are sometimes called class
methods and static variables are sometimes
called class variables
• Let's carefully consider the implications of
each
2015 @ Sonia Sousa 66
67. Static Variables
• Normally, each object has its own data space, but
if a variable is declared as static, only one copy of
the variable exists
private static float price;
• Memory space for a static variable is created
when the class is first referenced
• All objects instantiated from the class share its
static variables
• Changing the value of a static variable in one
object changes it for all others
2015 @ Sonia Sousa 67
68. Static Methods
• Because it is declared as static, the cube
method can be invoked through the class name:
value = Helper.cube(4);
public class Helper
{
public static int cube (int num)
{
return num * num * num;
}
}
2015 @ Sonia Sousa 68
69. Static Class Members
• The order of the modifiers can be interchanged,
but by convention visibility modifiers come first
• Recall that the main method is static – it is
invoked by the Java interpreter without creating an
object
• Static methods cannot reference instance
variables because instance variables don't exist
until an object exists
• However, a static method can reference static
variables or local variables
2015 @ Sonia Sousa 69
70. Static Class Members
• Static methods and static variables often
work together
• The following example keeps track of how
many Slogan objects have been created
using a static variable, and makes that
information available using a static method
• See SloganCounter.java
• See Slogan.java
2015 @ Sonia Sousa 70
71. //********************************************************************
// SloganCounter.java Author: Lewis/Loftus
//
// Demonstrates the use of the static modifier.
//********************************************************************
public class SloganCounter
{
//-----------------------------------------------------------------
// Creates several Slogan objects and prints the number of
// objects that were created.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Slogan obj;
obj = new Slogan ("Remember the Alamo.");
System.out.println (obj);
obj = new Slogan ("Don't Worry. Be Happy.");
System.out.println (obj);
continue
2015 @ Sonia Sousa 71
72. continue
obj = new Slogan ("Live Free or Die.");
System.out.println (obj);
obj = new Slogan ("Talk is Cheap.");
System.out.println (obj);
obj = new Slogan ("Write Once, Run Anywhere.");
System.out.println (obj);
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
2015 @ Sonia Sousa 72
73. continue
obj = new Slogan ("Live Free or Die.");
System.out.println (obj);
obj = new Slogan ("Talk is Cheap.");
System.out.println (obj);
obj = new Slogan ("Write Once, Run Anywhere.");
System.out.println (obj);
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
Output
Remember the Alamo.
Don't Worry. Be Happy.
Live Free or Die.
Talk is Cheap.
Write Once, Run Anywhere.
Slogans created: 5
2015 @ Sonia Sousa 73
74. @ Sonia Sousa
//********************************************************************
// Slogan.java Author: Lewis/Loftus
//
// Represents a single slogan string.
//********************************************************************
public class Slogan
{
private String phrase;
private static int count = 0;
//-----------------------------------------------------------------
// Constructor: Sets up the slogan and counts the number of
// instances created.
//-----------------------------------------------------------------
public Slogan (String str)
{
phrase = str;
count++;
}
continue
2015 74
75. continue
//-----------------------------------------------------------------
// Returns this slogan as a string.
//-----------------------------------------------------------------
public String toString()
{
return phrase;
}
//-----------------------------------------------------------------
// Returns the number of instances of this class that have been
// created.
//-----------------------------------------------------------------
public static int getCount ()
{
return count;
}
}
2015 @ Sonia Sousa 75
76. Quick Check
• Why can't a static method reference an instance
variable?
– Because instance data is created only when an
– object is created.
– You don't need an object to execute a static method.
– And even if you had an object, which object's instance
– data would be referenced? (remember, the method is
– invoked through the class name)
2015 @ Sonia Sousa 76
77. Lesson 7 - Outline
772015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
Extra
78. Wrapper Classes
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
• The java.lang package contains wrapper
classes that correspond to each primitive type:
2015 @ Sonia Sousa 78
79. Wrapper Classes
• The following declaration creates an Integer object
which represents the integer 40 as an object
Integer age = new Integer(40);
• An object of a wrapper class can be used in any
situation where a primitive value will not suffice
• For example, some objects serve as containers of
other objects
• Primitive values could not be stored in such
containers, but wrapper objects could be
792015 @ Sonia Sousa
80. Wrapper Classes
• Wrapper classes also contain static methods that help
manage the associated type
• For example, the Integer class contains a method to
convert an integer stored in a String to an int
value:
num = Integer.parseInt(str);
• They often contain useful constants as well
• For example, the Integer class contains MIN_VALUE
and MAX_VALUE which hold the smallest and largest
int values
802015 @ Sonia Sousa
81. Autoboxing
• Autoboxing is the automatic conversion of a primitive
value to a corresponding wrapper object:
Integer obj;
int num = 42;
obj = num;
• The assignment creates the appropriate Integer
object
• The reverse conversion (called unboxing) also occurs
automatically as needed
812015 @ Sonia Sousa
82. Quick Check
• Are the following assignments valid? Explain.
Double value = 15.75;
Character ch = new Character('T');
char myChar = ch;
822015 @ Sonia Sousa
83. Quick Check
• Are the following assignments valid? Explain.
– Double value = 15.75;
• Yes. The double literal is autoboxed into a
Double object.
– Character ch = new Character('T');
• Yes, the char in the object is unboxed before the
assignment.
– char myChar = ch;
832015 @ Sonia Sousa
84. Lesson 7 - Outline
842015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
Extra
85. Class Relationships
• Classes in a software system can have
various types of relationships to each other
• Three of the most common relationships:
– Dependency: A uses B
– Aggregation: A has-a B
– Inheritance: A is-a B
• Let's discuss dependency and aggregation
further
2015 @ Sonia Sousa 85
86. Dependency
• A dependency exists when one class relies on another
in some way, usually by invoking the methods of the
other
• We've seen dependencies in many previous examples
• We don't want numerous or complex dependencies
among classes
• Nor do we want complex classes that don't depend on
others
• A good design strikes the right balance
2015 @ Sonia Sousa 86
87. Dependency
• Some dependencies occur between objects
of the same class
• A method of the class may accept an object
of the same class as a parameter
• For example, the concat method of the
String class takes as a parameter another
String object
str3 = str1.concat(str2);
2015 @ Sonia Sousa 87
88. Dependency
• The following example defines a class called
RationalNumber
• A rational number is a value that can be
represented as the ratio of two integers
• Several methods of the RationalNumber class
accept another RationalNumber object as a
parameter
• See RationalTester.java
• See RationalNumber.java
2015 @ Sonia Sousa 88
89. //********************************************************************
// RationalTester.java Author: Lewis/Loftus
//
// Driver to exercise the use of multiple Rational objects.
//********************************************************************
public class RationalTester
{
//-----------------------------------------------------------------
// Creates some rational number objects and performs various
// operations on them.
//-----------------------------------------------------------------
public static void main (String[] args)
{
RationalNumber r1 = new RationalNumber (6, 8);
RationalNumber r2 = new RationalNumber (1, 3);
RationalNumber r3, r4, r5, r6, r7;
System.out.println ("First rational number: " + r1);
System.out.println ("Second rational number: " + r2);
continue
2015 @ Sonia Sousa 89
90. continue
if (r1.isLike(r2))
System.out.println ("r1 and r2 are equal.");
else
System.out.println ("r1 and r2 are NOT equal.");
r3 = r1.reciprocal();
System.out.println ("The reciprocal of r1 is: " + r3);
r4 = r1.add(r2);
r5 = r1.subtract(r2);
r6 = r1.multiply(r2);
r7 = r1.divide(r2);
System.out.println ("r1 + r2: " + r4);
System.out.println ("r1 - r2: " + r5);
System.out.println ("r1 * r2: " + r6);
System.out.println ("r1 / r2: " + r7);
}
}
2015 @ Sonia Sousa 90
91. continue
if (r1.isLike(r2))
System.out.println ("r1 and r2 are equal.");
else
System.out.println ("r1 and r2 are NOT equal.");
r3 = r1.reciprocal();
System.out.println ("The reciprocal of r1 is: " + r3);
r4 = r1.add(r2);
r5 = r1.subtract(r2);
r6 = r1.multiply(r2);
r7 = r1.divide(r2);
System.out.println ("r1 + r2: " + r4);
System.out.println ("r1 - r2: " + r5);
System.out.println ("r1 * r2: " + r6);
System.out.println ("r1 / r2: " + r7);
}
}
Output
First rational number: 3/4
Second rational number: 1/3
r1 and r2 are NOT equal.
The reciprocal of r1 is: 4/3
r1 + r2: 13/12
r1 - r2: 5/12
r1 * r2: 1/4
r1 / r2: 9/4
2015 @ Sonia Sousa 91
92. //********************************************************************
// RationalNumber.java Author: Lewis/Loftus
//
// Represents one rational number with a numerator and denominator.
//********************************************************************
public class RationalNumber
{
private int numerator, denominator;
//-----------------------------------------------------------------
// Constructor: Sets up the rational number by ensuring a nonzero
// denominator and making only the numerator signed.
//-----------------------------------------------------------------
public RationalNumber (int numer, int denom)
{
if (denom == 0)
denom = 1;
// Make the numerator "store" the sign
if (denom < 0)
{
numer = numer * -1;
denom = denom * -1;
}
continue
2015 @ Sonia Sousa 92
93. continue
numerator = numer;
denominator = denom;
reduce();
}
//-----------------------------------------------------------------
// Returns the numerator of this rational number.
//-----------------------------------------------------------------
public int getNumerator ()
{
return numerator;
}
//-----------------------------------------------------------------
// Returns the denominator of this rational number.
//-----------------------------------------------------------------
public int getDenominator ()
{
return denominator;
}
continue
2015 @ Sonia Sousa 93
94. continue
//-----------------------------------------------------------------
// Returns the reciprocal of this rational number.
//-----------------------------------------------------------------
public RationalNumber reciprocal ()
{
return new RationalNumber (denominator, numerator);
}
//-----------------------------------------------------------------
// Adds this rational number to the one passed as a parameter.
// A common denominator is found by multiplying the individual
// denominators.
//-----------------------------------------------------------------
public RationalNumber add (RationalNumber op2)
{
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int sum = numerator1 + numerator2;
return new RationalNumber (sum, commonDenominator);
}
continue
2015 @ Sonia Sousa 94
95. continue
//-----------------------------------------------------------------
// Subtracts the rational number passed as a parameter from this
// rational number.
//-----------------------------------------------------------------
public RationalNumber subtract (RationalNumber op2)
{
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int difference = numerator1 - numerator2;
return new RationalNumber (difference, commonDenominator);
}
//-----------------------------------------------------------------
// Multiplies this rational number by the one passed as a
// parameter.
//-----------------------------------------------------------------
public RationalNumber multiply (RationalNumber op2)
{
int numer = numerator * op2.getNumerator();
int denom = denominator * op2.getDenominator();
return new RationalNumber (numer, denom);
}
continue
2015 @ Sonia Sousa 95
96. continue
//-----------------------------------------------------------------
// Divides this rational number by the one passed as a parameter
// by multiplying by the reciprocal of the second rational.
//-----------------------------------------------------------------
public RationalNumber divide (RationalNumber op2)
{
return multiply (op2.reciprocal());
}
//-----------------------------------------------------------------
// Determines if this rational number is equal to the one passed
// as a parameter. Assumes they are both reduced.
//-----------------------------------------------------------------
public boolean isLike (RationalNumber op2)
{
return ( numerator == op2.getNumerator() &&
denominator == op2.getDenominator() );
}
continue
2015 @ Sonia Sousa 96
97. continue
//-----------------------------------------------------------------
// Returns this rational number as a string.
//-----------------------------------------------------------------
public String toString ()
{
String result;
if (numerator == 0)
result = "0";
else
if (denominator == 1)
result = numerator + "";
else
result = numerator + "/" + denominator;
return result;
}
continue
2015 @ Sonia Sousa 97
98. continue
//-----------------------------------------------------------------
// Reduces this rational number by dividing both the numerator
// and the denominator by their greatest common divisor.
//-----------------------------------------------------------------
private void reduce ()
{
if (numerator != 0)
{
int common = gcd (Math.abs(numerator), denominator);
numerator = numerator / common;
denominator = denominator / common;
}
}
continue
2015 @ Sonia Sousa 98
99. continue
//-----------------------------------------------------------------
// Computes and returns the greatest common divisor of the two
// positive parameters. Uses Euclid's algorithm.
//-----------------------------------------------------------------
private int gcd (int num1, int num2)
{
while (num1 != num2)
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
return num1;
}
}
2015 @ Sonia Sousa 99
100. Aggregation
• An aggregate is an object that is made up of
other objects
• Therefore aggregation is a has-a relationship
– A car has a chassis
• An aggregate object contains references to
other objects as instance data
• This is a special kind of dependency; the
aggregate relies on the objects that compose
it
2015 @ Sonia Sousa 100
101. Aggregation
• In the following example, a Student object
is composed, in part, of Address objects
• A student has an address (in fact each
student has two addresses)
• See StudentBody.java
• See Student.java
• See Address.java
2015 @ Sonia Sousa 101
102. //********************************************************************
// StudentBody.java Author: Lewis/Loftus
//
// Demonstrates the use of an aggregate class.
//********************************************************************
public class StudentBody
{
//-----------------------------------------------------------------
// Creates some Address and Student objects and prints them.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Address school = new Address ("800 Lancaster Ave.", "Villanova",
"PA", 19085);
Address jHome = new Address ("21 Jump Street", "Lynchburg",
"VA", 24551);
Student john = new Student ("John", "Smith", jHome, school);
Address mHome = new Address ("123 Main Street", "Euclid", "OH",
44132);
Student marsha = new Student ("Marsha", "Jones", mHome, school);
System.out.println (john);
System.out.println ();
System.out.println (marsha);
}
}
2015 @ Sonia Sousa 102
103. //********************************************************************
// StudentBody.java Author: Lewis/Loftus
//
// Demonstrates the use of an aggregate class.
//********************************************************************
public class StudentBody
{
//-----------------------------------------------------------------
// Creates some Address and Student objects and prints them.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Address school = new Address ("800 Lancaster Ave.", "Villanova",
"PA", 19085);
Address jHome = new Address ("21 Jump Street", "Lynchburg",
"VA", 24551);
Student john = new Student ("John", "Smith", jHome, school);
Address mHome = new Address ("123 Main Street", "Euclid", "OH",
44132);
Student marsha = new Student ("Marsha", "Jones", mHome, school);
System.out.println (john);
System.out.println ();
System.out.println (marsha);
}
}
Output
John Smith
Home Address:
21 Jump Street
Lynchburg, VA 24551
School Address:
800 Lancaster Ave.
Villanova, PA 19085
Marsha Jones
Home Address:
123 Main Street
Euclid, OH 44132
School Address:
800 Lancaster Ave.
Villanova, PA 19085
2015 @ Sonia Sousa 103
104. //********************************************************************
// Student.java Author: Lewis/Loftus
//
// Represents a college student.
//********************************************************************
public class Student
{
private String firstName, lastName;
private Address homeAddress, schoolAddress;
//-----------------------------------------------------------------
// Constructor: Sets up this student with the specified values.
//-----------------------------------------------------------------
public Student (String first, String last, Address home,
Address school)
{
firstName = first;
lastName = last;
homeAddress = home;
schoolAddress = school;
}
continue
2015 @ Sonia Sousa 104
105. continue
//-----------------------------------------------------------------
// Returns a string description of this Student object.
//-----------------------------------------------------------------
public String toString()
{
String result;
result = firstName + " " + lastName + "n";
result += "Home Address:n" + homeAddress + "n";
result += "School Address:n" + schoolAddress;
return result;
}
}
2015 @ Sonia Sousa 105
106. //********************************************************************
// Address.java Author: Lewis/Loftus
//
// Represents a street address.
//********************************************************************
public class Address
{
private String streetAddress, city, state;
private long zipCode;
//-----------------------------------------------------------------
// Constructor: Sets up this address with the specified data.
//-----------------------------------------------------------------
public Address (String street, String town, String st, long zip)
{
streetAddress = street;
city = town;
state = st;
zipCode = zip;
}
continue
2015 @ Sonia Sousa 106
109. The this Reference
• The this reference allows an object to refer to itself
• That is, the this reference, used inside a method,
refers to the object through which the method is being
executed
• Suppose the this reference is used inside a method
called tryMe, which is invoked as follows:
obj1.tryMe();
obj2.tryMe();
• In the first invocation, the this reference refers to
obj1; in the second it refers to obj2
2015 @ Sonia Sousa 109
110. The this reference
• The this reference can be used to distinguish the
instance variables of a class from corresponding
method parameters with the same names
• The constructor of the Account class from Chapter 4
could have been written as follows:
public Account (String name, long acctNumber,
double balance)
{
this.name = name;
this.acctNumber = acctNumber;
this.balance = balance;
}
2015 @ Sonia Sousa 110
111. Lesson 7 - Outline
1112015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
112. Anatomy of a Class
Additional examples
2015 @ Sonia Sousa 112
113. // StudentManager.java Author: Isaias Barreto da Rosa
//
// Demonstrates the creation and use of a user-defined class.
package studentmanager;
import java.util.Scanner;
public class StudentManager {
// Compares the grades of two students and tells who is the best
static void compareStudents(Student st1, Student st2)
{
if (st1.getGrade() > st2.getGrade())
{ System.out.print(st1.getName +" is a better student");}
else
{
if (st2.getGrade() > st1.geGrade())
{System.out.print(st2.getName() +" is a better student");}
else
{System.out.println(st1.getNname() + " and " + st2.getName()
+ "are on the same level");}
}
}
113@ Sonia Sousa2015
continue
114. Continue
public static void main(String[] args) {
Student st1, st2, st3;
String name;
double grade;
Scanner scan = new Scanner(System.in);
System.out.println("Insert the first name for Student 1");
name = scan.nextLine();
System.out.println("Insert the grade for Student 1");
grade = scan.nextDouble();
st1 = new Student(name,grade);
System.out.println("Insert the first name for Student 2");
name = scan.nextLine();
System.out.println("Insert the grade for Student 2");
grade = scan.nextDouble();
st2 = new Student(name,grade);
compareStudents(st1,st2);
}
}
114@ Sonia Sousa2015
115. class Student{
private String name;
private double grade;
public final double MAXGRADE=20;
// Constructor: Sets the student’s name and initial grade.
public Student (String name1, double grade1){
name = name1;
grade = grade1;
}
// Returns the student's name
String getName(){ return name;}
// Returns the student's grade
double getGrade(){return grade;}
// Increase the studens's grade
double increaseGrade(){
if (grade < MAXGRADE);
{grade++;}
return grade;
}
}
115@ Sonia Sousa2015
Continue
116. Data Scope
• The scope of data is the area in a program in which
that data can be referenced (used)
• Data declared at the class level can be referenced by
all methods in that class
• Data declared within a method can be used only in
that method
• Data declared within a method is called local data
• In the compareStudents class, the variable scan
is declared inside the main method -- it is local to that
method and cannot be referenced anywhere else
116@ Sonia Sousa2015
117. Instance Data
• A variable declared at the class level (such as name) is called
class attribute or instance variable
• Each instance (object) has its own instance variable
• A class declares the type of the data, but it does not reserve
memory space for it
• Each time a Student object is created, a new name
variable is created as well
• The objects of a class share the method definitions, but each
object has its own data space
• That's the only way two objects can have different states
117@ Sonia Sousa2015
119. @ Sonia Sousa
//********************************************************************
// RollingDice.java Author: Lewis/Loftus
//
// Demonstrates the creation and use of a user-defined class.
//********************************************************************
public class RollingDice
{
//-----------------------------------------------------------------
// Creates two Die objects and rolls them several times.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Die die1, die2;
int sum;
die1 = new Die();
die2 = new Die();
die1.roll();
die2.roll();
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
continue
1192015
121. continue
die1.roll();
die2.setFaceValue(4);
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
sum = die1.getFaceValue() + die2.getFaceValue();
System.out.println ("Sum: " + sum);
sum = die1.roll() + die2.roll();
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
System.out.println ("New sum: " + sum);
}
}
Sample Run
Die One: 5, Die Two: 2
Die One: 1, Die Two: 4
Sum: 5
Die One: 4, Die Two: 2
New sum: 6
@ Sonia Sousa 1212015
122. //********************************************************************
// Die.java Author: Lewis/Loftus
//
// Represents one die (singular of dice) with faces showing values
// between 1 and 6.
//********************************************************************
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: Sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
continue
@ Sonia Sousa 1222015
123. continue
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue (int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getFaceValue()
{
return faceValue;
}
continue
@ Sonia Sousa 1232015
125. The toString Method
• It's good practice to define a toString
method for a class
• The toString method returns a character
string that represents the object in some way
• It is called automatically when an object is
concatenated to a string or when it is passed
to the println method
• It's also convenient for debugging problems
@ Sonia Sousa 1252015
126. Data Scope
• The scope of data is the area in a program in which
that data can be referenced (used)
• Data declared at the class level can be referenced by
all methods in that class
• Data declared within a method can be used only in
that method
• Data declared within a method is called local data
• In the Die class, the variable result is declared
inside the toString method -- it is local to that
method and cannot be referenced anywhere else
@ Sonia Sousa 1262015
127. Instance Data
• A variable declared at the class level (such as faceValue) is
called instance data
• Each instance (object) has its own instance variable
• A class declares the type of the data, but it does not reserve
memory space for it
• Each time a Die object is created, a new faceValue
variable is created as well
• The objects of a class share the method definitions, but each
object has its own data space
• That's the only way two objects can have different states
@ Sonia Sousa 1272015
128. UML Diagrams
• UML stands for the Unified Modeling Language
• UML diagrams show relationships among classes
and objects
• A UML class diagram consists of one or more
classes, each with sections for the class name,
attributes (data), and operations (methods)
• Lines between classes represent associations
• A dotted arrow shows that one class uses the
other (calls its methods)
@ Sonia Sousa 1282015
129. UML Class Diagrams
• A UML class diagram for the RollingDice
program:
RollingDice
main (args : String[]) : void
Die
faceValue : int
roll() : int
1292015 @ Sonia Sousa
3-129