This document discusses object-oriented programming concepts in Java including objects, classes, and how to define classes and create objects. It provides examples of defining a Circle class with attributes like radius and methods like getArea(). It then demonstrates how to create Circle objects, access object attributes, and invoke methods. Key points covered include using constructors to initialize objects, declaring object reference variables, and tracing example code to create and manipulate objects.
Java™ (OOP) - Chapter 8: "Objects and Classes"Gouda Mando
After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. Suppose you want to develop a graphical user interface as shown below. How do you program it?
This document introduces key concepts of object-oriented programming in Java including classes, objects, encapsulation, and inheritance. It discusses how classes are used to define objects and their properties (data fields) and behaviors (methods). Constructors are introduced as special methods used to initialize objects. The document provides examples of defining classes like Circle and TV, creating objects, and accessing object data and methods. It also discusses reference variables, the null value, default values, and differences between primitive types and reference types. Finally, core classes like Date, Random, and JFrame from the Java library are mentioned.
The document discusses arrays in Java. It begins by introducing arrays as data structures that hold a collection of the same type of data elements. It then covers how to declare, create, initialize and access array elements using indexed variables. The document explains using array initializers to declare, create and initialize an array in one statement. It also discusses default element values, finding an array's length, and examples of using arrays in programs including a detailed step-by-step trace of an array example program.
This document discusses inheritance and polymorphism in Java. It describes using inheritance to define subclasses that extend existing superclasses in order to avoid code redundancy when multiple classes share common properties and behaviors. The key concepts covered include defining subclasses, invoking superclass constructors and methods using the super keyword, overriding methods in subclasses, polymorphism and dynamic binding, and casting between subclasses and superclasses.
This document summarizes Chapter 6 of Liang's Introduction to Java Programming, Ninth Edition. It introduces arrays as a data structure that represents a collection of the same type of data. It describes how to declare array variables, create arrays, initialize arrays, access array elements using indexes, and use array initializers. It also provides examples of common array operations and how to trace a sample program that uses arrays.
This chapter discusses object-oriented programming concepts in Java including immutable objects, scope of variables, the this keyword, class abstraction, composition relationships, and designing classes. It provides examples of how to model real-world entities like loans, BMI calculations, stacks, and dates using object-oriented design principles such as encapsulation, abstraction and separation of concerns. The key benefits of object-oriented programming highlighted are reusability, flexibility and modularity in building software.
This document discusses chapters and concepts from Liang's Introduction to Java Programming textbook. It covers defining and using methods in Java, including defining methods with parameters and return types, invoking methods by passing arguments, and how method calls are handled by the call stack. Key points covered include formal vs actual parameters, method signatures, return values, and reusing methods from other classes. Examples are provided to demonstrate calculating sums and finding maximum values using methods.
Java™ (OOP) - Chapter 10: "Thinking in Objects"Gouda Mando
You see the advantages of object-oriented programming from the preceding two chapters. This chapter will demonstrate how to solve problems using the object-oriented paradigm. Before studying these examples, we first introduce several language features for supporting these examples.
Java™ (OOP) - Chapter 8: "Objects and Classes"Gouda Mando
After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. Suppose you want to develop a graphical user interface as shown below. How do you program it?
This document introduces key concepts of object-oriented programming in Java including classes, objects, encapsulation, and inheritance. It discusses how classes are used to define objects and their properties (data fields) and behaviors (methods). Constructors are introduced as special methods used to initialize objects. The document provides examples of defining classes like Circle and TV, creating objects, and accessing object data and methods. It also discusses reference variables, the null value, default values, and differences between primitive types and reference types. Finally, core classes like Date, Random, and JFrame from the Java library are mentioned.
The document discusses arrays in Java. It begins by introducing arrays as data structures that hold a collection of the same type of data elements. It then covers how to declare, create, initialize and access array elements using indexed variables. The document explains using array initializers to declare, create and initialize an array in one statement. It also discusses default element values, finding an array's length, and examples of using arrays in programs including a detailed step-by-step trace of an array example program.
This document discusses inheritance and polymorphism in Java. It describes using inheritance to define subclasses that extend existing superclasses in order to avoid code redundancy when multiple classes share common properties and behaviors. The key concepts covered include defining subclasses, invoking superclass constructors and methods using the super keyword, overriding methods in subclasses, polymorphism and dynamic binding, and casting between subclasses and superclasses.
This document summarizes Chapter 6 of Liang's Introduction to Java Programming, Ninth Edition. It introduces arrays as a data structure that represents a collection of the same type of data. It describes how to declare array variables, create arrays, initialize arrays, access array elements using indexes, and use array initializers. It also provides examples of common array operations and how to trace a sample program that uses arrays.
This chapter discusses object-oriented programming concepts in Java including immutable objects, scope of variables, the this keyword, class abstraction, composition relationships, and designing classes. It provides examples of how to model real-world entities like loans, BMI calculations, stacks, and dates using object-oriented design principles such as encapsulation, abstraction and separation of concerns. The key benefits of object-oriented programming highlighted are reusability, flexibility and modularity in building software.
This document discusses chapters and concepts from Liang's Introduction to Java Programming textbook. It covers defining and using methods in Java, including defining methods with parameters and return types, invoking methods by passing arguments, and how method calls are handled by the call stack. Key points covered include formal vs actual parameters, method signatures, return values, and reusing methods from other classes. Examples are provided to demonstrate calculating sums and finding maximum values using methods.
Java™ (OOP) - Chapter 10: "Thinking in Objects"Gouda Mando
You see the advantages of object-oriented programming from the preceding two chapters. This chapter will demonstrate how to solve problems using the object-oriented paradigm. Before studying these examples, we first introduce several language features for supporting these examples.
The document discusses selection control statements in Java including if, if-else, and switch statements. It provides examples of using boolean expressions and comparison operators to write conditional logic. Key topics covered include one-way if statements, two-way if-else statements, nested if statements, avoiding common errors, and using logical operators to combine conditions. Examples provided demonstrate how to use random numbers and selection statements to create simple math quiz programs.
This document discusses Chapter 2 of an introduction to Java programming textbook. It covers elementary programming concepts such as writing simple Java programs to perform computations, using variables to store data, numeric data types, operators, and literals. The chapter objectives are to learn how to solve practical problems by working with Java primitive data types, variables, input/output, and other basic programming elements.
This document summarizes a lecture on object-oriented programming concepts including classes, methods, constructors, and objects.
The lecture covered:
1) The components of a class including fields, methods, and constructors. Main(), setter, and getter methods were discussed.
2) How to call methods within the same class and between different classes.
3) How to create objects from classes and how messages are sent to objects to invoke their methods.
This document discusses two-dimensional arrays in Java. It begins by providing motivations for using two-dimensional arrays to represent matrices and tables. It then outlines the objectives of the chapter, which include declaring and initializing two-dimensional arrays, common operations on them like printing and summing elements, passing them as parameters to methods, and using them to solve problems like grading multiple choice tests and finding closest pairs of points. The document provides examples of declaring, initializing, accessing elements of, and performing operations on two-dimensional arrays in Java.
Inheritance allows classes to extend and inherit properties from base classes. This creates class hierarchies where subclasses inherit and can override methods from superclasses. Inheritance promotes code reuse through extension when subclasses share the same role as the base class. Composition and delegation are alternative approaches to code reuse that may be preferable in some cases over inheritance.
Encapsulation provides benefits such as reducing complexity, ensuring structural changes remain local, and allowing for validation and data binding. It works by hiding implementation details and wrapping code and data together. Objects use private fields and public getters/setters for access. Access modifiers like private, protected, and public control visibility. Validation occurs in setters through exceptions. Mutable objects can be modified after creation while immutable objects cannot. The final keyword prevents inheritance, method overriding, or variable reassignment.
This document provides an overview of the Java Collections Framework. It discusses the main interfaces like Collection, List, Set, Map and their implementing classes like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap. It also covers topics like iterators, choosing appropriate collections, and using stacks, queues and priority queues. Examples are provided to demonstrate working with sets, maps, and using collections for problems like spell checking. The document aims to teach how to use the collection classes provided in the Java library and choose appropriate collections to solve programming problems.
Here we are going to learn why is a good practice to use interfaces and how they are different from abstraction classes. Further more we are going to see how which one of them to use.
The document discusses object-oriented programming concepts like objects, classes, and encapsulation. It provides examples of a Circle class to illustrate these concepts. The Circle class defines data fields like radius and methods like getArea(). Objects of the Circle class can be created, each with their own radius value. The document emphasizes that classes should encapsulate data to prevent direct modification and make the code easier to maintain. It also covers other class concepts like constructors, the dot operator, constant object names, and inline functions.
This document discusses arrays and array lists in Java. It covers how to declare and initialize arrays, access array elements using indexes, and common array algorithms. The key points covered include:
- Arrays collect a sequence of values of the same type and are initialized using syntax like new double[10].
- Individual array elements are accessed using an integer index and the [] operator (e.g. array[i]).
- The enhanced for loop provides a simplified way to traverse all elements of an array without using indexes.
- Arrays can be passed as arguments to and returned from methods. Partially filled arrays require tracking the number of elements using a companion variable.
This document discusses loops in programming. It covers while loops, for loops, and do-while loops. It provides examples of using these loops to calculate investment growth over multiple years. Key points covered include initializing and updating loop counters, checking loop conditions, and hand tracing code execution to identify errors. Nested loops and common loop errors like infinite loops are also discussed.
The document discusses various types of arrays in Java, including one-dimensional arrays, multi-dimensional arrays, and jagged arrays. It explains how to declare, initialize, access, and pass array elements. Key points include that arrays are dynamically allocated objects that can store primitive values or objects, arrays inherit from Object and implement Serializable and Cloneable, and the class name of an array returns [ followed by the data type (e.g. [I for int array). The document also demonstrates various array examples using for loops and exceptions like ArrayIndexOutOfBoundsException.
The document discusses key concepts in object-oriented programming including creating objects and object reference variables, constructors, modifiers, instance and class variables and methods, scope of variables, and using the this keyword. It provides examples of creating Circle and Mortgage classes to demonstrate these concepts. UML diagrams are used to illustrate graphical notations for classes, objects, fields, and methods.
The document discusses designing good object-oriented classes. It provides guidance on choosing appropriate classes, maintaining cohesion so that classes represent single concepts, minimizing dependencies between classes, and reducing side effects from method calls. Examples are given for common patterns when designing classes, such as keeping a running total, counting events, collecting object values, managing object properties, modeling object states, and describing an object's position. The reader is taught how to apply these design principles and patterns when modeling real-world problems as classes, methods, and objects.
In this chapter we are going to get familiar with the basic concepts of object-oriented programming – classes and objects – and we are going to explain how to use classes from the standard libraries of .NET Framework. We are going to mention some commonly used system classes and see how to create and use their instances (objects). We are going to discuss how we can access fields of an object, how to call constructors and how to work with static fields in classes. Finally, we are going to get familiar with the term "namespaces" – how they help us, how to include them and use them.
This document discusses polymorphism, abstract classes, and abstract methods. It defines polymorphism as an object's ability to take on many forms and describes how it allows reference variables to refer to objects of child classes. It also distinguishes between method overloading and overriding, and explains the rules for each. Abstract classes are introduced as classes that cannot be instantiated directly but can be inherited from, and it is noted they may or may not contain abstract methods.
The Ring programming language version 1.5.1 book - Part 69 of 180Mahmoud Samir Fayed
This document discusses Ring's variable scoping rules and how they apply when defining classes and methods. It addresses potential conflicts that can arise between global variables, class attributes, and local variables. Several solutions are presented for resolving conflicts, such as using self references, changing variable names, or defining setter methods. Best practices are recommended like avoiding global variables when possible and using a dollar sign prefix for global variable names.
This document discusses inheritance and polymorphism in Java. It begins by introducing the motivations for inheritance, which is to avoid redundancy when designing classes that share common features, like circles, rectangles, and triangles. It then lists the chapter objectives, which include defining subclasses, invoking superclass constructors and methods, overriding methods, polymorphism, and other inheritance-related concepts. The document provides an example of superclass GeometricObject and subclasses Circle and Rectangle. It also discusses that superclass constructors are not inherited by subclasses but must be invoked explicitly or implicitly using the super keyword.
| 5 countries, 5 wines and 5 varieties to taste in a month or todayDavid Ridings
Anna von Bertele recommends 5 wines from 5 different countries to try in order to sound self-assured when ordering or discussing wine. She recommends a 2012 Syrah from Mas Coutelou in France's Languedoc region, a Gruner Weltliner from Ebner-Ebenauer in Austria, Josh Bergstrom's Old Stones Chardonnay from Oregon in the USA, a Pinot Noir such as 'Cornish Point' from Felton Road in New Zealand, and Craig Hawkins' unusual "El Bandito 'Cortez'" Chenin Blanc from South Africa.
The document discusses selection control statements in Java including if, if-else, and switch statements. It provides examples of using boolean expressions and comparison operators to write conditional logic. Key topics covered include one-way if statements, two-way if-else statements, nested if statements, avoiding common errors, and using logical operators to combine conditions. Examples provided demonstrate how to use random numbers and selection statements to create simple math quiz programs.
This document discusses Chapter 2 of an introduction to Java programming textbook. It covers elementary programming concepts such as writing simple Java programs to perform computations, using variables to store data, numeric data types, operators, and literals. The chapter objectives are to learn how to solve practical problems by working with Java primitive data types, variables, input/output, and other basic programming elements.
This document summarizes a lecture on object-oriented programming concepts including classes, methods, constructors, and objects.
The lecture covered:
1) The components of a class including fields, methods, and constructors. Main(), setter, and getter methods were discussed.
2) How to call methods within the same class and between different classes.
3) How to create objects from classes and how messages are sent to objects to invoke their methods.
This document discusses two-dimensional arrays in Java. It begins by providing motivations for using two-dimensional arrays to represent matrices and tables. It then outlines the objectives of the chapter, which include declaring and initializing two-dimensional arrays, common operations on them like printing and summing elements, passing them as parameters to methods, and using them to solve problems like grading multiple choice tests and finding closest pairs of points. The document provides examples of declaring, initializing, accessing elements of, and performing operations on two-dimensional arrays in Java.
Inheritance allows classes to extend and inherit properties from base classes. This creates class hierarchies where subclasses inherit and can override methods from superclasses. Inheritance promotes code reuse through extension when subclasses share the same role as the base class. Composition and delegation are alternative approaches to code reuse that may be preferable in some cases over inheritance.
Encapsulation provides benefits such as reducing complexity, ensuring structural changes remain local, and allowing for validation and data binding. It works by hiding implementation details and wrapping code and data together. Objects use private fields and public getters/setters for access. Access modifiers like private, protected, and public control visibility. Validation occurs in setters through exceptions. Mutable objects can be modified after creation while immutable objects cannot. The final keyword prevents inheritance, method overriding, or variable reassignment.
This document provides an overview of the Java Collections Framework. It discusses the main interfaces like Collection, List, Set, Map and their implementing classes like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap. It also covers topics like iterators, choosing appropriate collections, and using stacks, queues and priority queues. Examples are provided to demonstrate working with sets, maps, and using collections for problems like spell checking. The document aims to teach how to use the collection classes provided in the Java library and choose appropriate collections to solve programming problems.
Here we are going to learn why is a good practice to use interfaces and how they are different from abstraction classes. Further more we are going to see how which one of them to use.
The document discusses object-oriented programming concepts like objects, classes, and encapsulation. It provides examples of a Circle class to illustrate these concepts. The Circle class defines data fields like radius and methods like getArea(). Objects of the Circle class can be created, each with their own radius value. The document emphasizes that classes should encapsulate data to prevent direct modification and make the code easier to maintain. It also covers other class concepts like constructors, the dot operator, constant object names, and inline functions.
This document discusses arrays and array lists in Java. It covers how to declare and initialize arrays, access array elements using indexes, and common array algorithms. The key points covered include:
- Arrays collect a sequence of values of the same type and are initialized using syntax like new double[10].
- Individual array elements are accessed using an integer index and the [] operator (e.g. array[i]).
- The enhanced for loop provides a simplified way to traverse all elements of an array without using indexes.
- Arrays can be passed as arguments to and returned from methods. Partially filled arrays require tracking the number of elements using a companion variable.
This document discusses loops in programming. It covers while loops, for loops, and do-while loops. It provides examples of using these loops to calculate investment growth over multiple years. Key points covered include initializing and updating loop counters, checking loop conditions, and hand tracing code execution to identify errors. Nested loops and common loop errors like infinite loops are also discussed.
The document discusses various types of arrays in Java, including one-dimensional arrays, multi-dimensional arrays, and jagged arrays. It explains how to declare, initialize, access, and pass array elements. Key points include that arrays are dynamically allocated objects that can store primitive values or objects, arrays inherit from Object and implement Serializable and Cloneable, and the class name of an array returns [ followed by the data type (e.g. [I for int array). The document also demonstrates various array examples using for loops and exceptions like ArrayIndexOutOfBoundsException.
The document discusses key concepts in object-oriented programming including creating objects and object reference variables, constructors, modifiers, instance and class variables and methods, scope of variables, and using the this keyword. It provides examples of creating Circle and Mortgage classes to demonstrate these concepts. UML diagrams are used to illustrate graphical notations for classes, objects, fields, and methods.
The document discusses designing good object-oriented classes. It provides guidance on choosing appropriate classes, maintaining cohesion so that classes represent single concepts, minimizing dependencies between classes, and reducing side effects from method calls. Examples are given for common patterns when designing classes, such as keeping a running total, counting events, collecting object values, managing object properties, modeling object states, and describing an object's position. The reader is taught how to apply these design principles and patterns when modeling real-world problems as classes, methods, and objects.
In this chapter we are going to get familiar with the basic concepts of object-oriented programming – classes and objects – and we are going to explain how to use classes from the standard libraries of .NET Framework. We are going to mention some commonly used system classes and see how to create and use their instances (objects). We are going to discuss how we can access fields of an object, how to call constructors and how to work with static fields in classes. Finally, we are going to get familiar with the term "namespaces" – how they help us, how to include them and use them.
This document discusses polymorphism, abstract classes, and abstract methods. It defines polymorphism as an object's ability to take on many forms and describes how it allows reference variables to refer to objects of child classes. It also distinguishes between method overloading and overriding, and explains the rules for each. Abstract classes are introduced as classes that cannot be instantiated directly but can be inherited from, and it is noted they may or may not contain abstract methods.
The Ring programming language version 1.5.1 book - Part 69 of 180Mahmoud Samir Fayed
This document discusses Ring's variable scoping rules and how they apply when defining classes and methods. It addresses potential conflicts that can arise between global variables, class attributes, and local variables. Several solutions are presented for resolving conflicts, such as using self references, changing variable names, or defining setter methods. Best practices are recommended like avoiding global variables when possible and using a dollar sign prefix for global variable names.
This document discusses inheritance and polymorphism in Java. It begins by introducing the motivations for inheritance, which is to avoid redundancy when designing classes that share common features, like circles, rectangles, and triangles. It then lists the chapter objectives, which include defining subclasses, invoking superclass constructors and methods, overriding methods, polymorphism, and other inheritance-related concepts. The document provides an example of superclass GeometricObject and subclasses Circle and Rectangle. It also discusses that superclass constructors are not inherited by subclasses but must be invoked explicitly or implicitly using the super keyword.
| 5 countries, 5 wines and 5 varieties to taste in a month or todayDavid Ridings
Anna von Bertele recommends 5 wines from 5 different countries to try in order to sound self-assured when ordering or discussing wine. She recommends a 2012 Syrah from Mas Coutelou in France's Languedoc region, a Gruner Weltliner from Ebner-Ebenauer in Austria, Josh Bergstrom's Old Stones Chardonnay from Oregon in the USA, a Pinot Noir such as 'Cornish Point' from Felton Road in New Zealand, and Craig Hawkins' unusual "El Bandito 'Cortez'" Chenin Blanc from South Africa.
Forces and motion are discussed. Key points include:
- Velocity is speed in a stated direction and acceleration is the rate of change of velocity over time.
- A bus accelerates from 5 m/s to 25 m/s in 10s, so its acceleration is 2 m/s2. A lizard accelerates from 8 m/s to 20 m/s in 4s, so its average acceleration is 3 m/s2.
- Acceleration can be calculated from the gradient of a velocity-time graph. The area under a velocity-time graph equals the distance traveled.
This study examined the feasibility of using chayote peelings as an alternative exfoliant. Three trials were conducted using different mixtures of chayote extract, olive oil, beeswax, and water. The third trial, which used the same mixture as the first trial but added lemon zest, produced an exfoliant with the best cream-like consistency and texture that was most similar to commercial products. The researchers concluded that chayote can effectively be used as an exfoliant substitute. They recommended further research using other vegetable peelings or improved procedures to develop an even more efficient exfoliant product.
Nuclear fission involves splitting atomic nuclei of uranium-235 or plutonium-239 when they absorb a neutron, causing the nucleus to split into smaller nuclei along with additional neutrons and energy release. This splitting can trigger a chain reaction where the released neutrons cause further fissions and more energy release.
09slide.ppt oops classes and objects conceptkavitamittal18
This document discusses object-oriented programming concepts in Java, including classes, objects, and the relationships between them. It introduces the Circle class as an example, explaining that a class acts as a template for objects and defines their data fields and methods. It also discusses how to define classes, create objects from classes using constructors, and access objects' members via reference variables. Key concepts covered include objects having state represented by data fields and behavior defined through methods.
The document discusses object-oriented programming concepts in Java, including classes, objects, and constructors. It defines a class as a template that defines the data fields and methods common to all objects of that type. An object is an instance of a class that contains the object's current state data. Constructors are special methods used to initialize new objects. The document provides examples of defining a Circle class and creating Circle objects using constructors. It also shows how to define classes graphically using UML class diagrams.
Classes in Java serve as templates for objects and allow programmers to define data types for their programs. A class defines fields to store data and methods to operate on that data. Programmers can then create objects from a class, which allocate memory and allow access to fields and calling of methods. Java handles memory management automatically by freeing up space for objects no longer being used.
To write Java programs to perform simple calculations (§2.2).
To obtain input from the console using the Scanner class (§2.3).
To use identifiers to name variables, constants, methods, and classes (§2.4).
To use variables to store data (§§2.5-2.6).
To program with assignment statements and assignment expressions (§2.6).
To use constants to store permanent data (§2.7).
To declare Java primitive data types: byte, short, int, long, float, double, and char (§§2.8.1).
To use Java operators to write numeric expressions (§§2.8.2–2.8.3).
To display current time (§2.9).
To use short hand operators (§2.10).
To cast value of one type to another type (§2.11).
To compute loan payment (§2.12).
To represent characters using the char type (§2.13).
To compute monetary changes (§2.14).
To represent a string using the String type (§2.15).
To become familiar with Java documentation, programming style, and naming conventions (§2.16).
To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17).
(GUI) To obtain input using the JOptionPane input dialog boxes (§2.18).
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.
This document summarizes Chapter 10 of Liang's Introduction to Java Programming textbook. It discusses key concepts in object-oriented programming like immutable objects, scope of variables, the this keyword, class abstraction, and composition relationships. It provides examples of how to create immutable classes, use this to reference instance variables and call constructors, and model relationships between classes using composition. The chapter aims to demonstrate how to solve problems using the object-oriented paradigm in Java.
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Gouda Mando
The document discusses strings and text input/output in Java. It introduces the String class and how to use it to process strings through methods like length(), charAt(), concat(), and substring(). It also covers comparing strings with equals() and compareTo(), as well as finding and replacing substrings. The chapter describes reading from and writing to files using classes like PrintWriter and Scanner.
This document discusses objects and classes in Java. It introduces object-oriented programming concepts like objects having state in the form of data fields and behavior in the form of methods. Classes are used to define objects of the same type by specifying their data fields and methods. The document provides examples of defining a Circle class and creating Circle objects that demonstrate accessing object data and using methods. It also explains concepts like constructors, which are special methods used to initialize objects when they are created.
This document provides an overview of object-oriented programming concepts such as classes, objects, methods, and constructors. It discusses how classes are templates that define common properties and behaviors for objects through data fields and methods. Objects are instances of classes that can access these data fields and methods. The document uses examples like a Circle class to demonstrate how to define classes, declare objects, and invoke methods.
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
This document summarizes Chapter 7 of Liang's Introduction to Java Programming textbook. It discusses representing data using two-dimensional arrays, declaring and initializing two-dimensional arrays, accessing elements, common operations like summing and shuffling, and examples like grading exams and solving Sudoku puzzles using two-dimensional arrays.
This document discusses defining classes in Java. It covers:
1. How classes are used to define new types and encapsulate data and methods.
2. The basic structure of a class including fields, methods, and constructors.
3. How to define classes, create objects from classes, and access fields and methods of objects.
This document discusses classes and objects in Java. It introduces classes as templates that define an object's state via fields and behavior via methods. An example Circle class is used to demonstrate how to declare fields for the circle's center and radius, and methods to calculate the circumference and area. The document also explains how to create Circle objects, access an object's fields and methods, and use the Circle class in a sample program.
This document introduces classes and objects in Java. It defines a class as a collection of fields and methods that operate on those fields. It shows how to define a Circle class with fields for the x and y coordinates and radius, and methods to calculate the circumference and area. It demonstrates how to create Circle objects, access the object fields and methods, and use the Circle class in a sample program.
The document introduces classes and objects in Java. It defines a class as a collection of fields (data) and methods (procedures or functions) that operate on that data. An example Circle class is provided with fields for the x and y coordinates of the center and the radius, and methods to calculate the circumference and area. To use a class, objects must be created from it using the new keyword, which allocates memory and returns a reference to the object. Methods can then be called and fields accessed via the object reference.
This document summarizes Chapter 7 of Liang's Introduction to Java Programming textbook. It discusses single-dimensional arrays, including declaring and creating arrays, accessing array elements using indexes, initializing arrays, and common array operations like finding minimum/maximum elements and shifting elements. The objectives cover array fundamentals as well as applying arrays to problems and using methods with array arguments and return values.
The document discusses introductory programming concepts in Java including variables, data types, operators, input/output, and more. It covers defining and initializing variables, numeric data types like int and double, arithmetic operators, reading user input, literals, and examples of simple programs to calculate areas and display time. The overall goal is to teach students how to solve practical problems by learning Java programming fundamentals.
The document discusses objects and classes in object-oriented programming, explaining that classes define templates for objects with data fields and methods, objects are instances of classes that contain state in their data fields and behavior through methods, and constructors are used to initialize objects when they are created from a class.
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyScyllaDB
Freshworks creates AI-boosted business software that helps employees work more efficiently and effectively. Managing data across multiple RDBMS and NoSQL databases was already a challenge at their current scale. To prepare for 10X growth, they knew it was time to rethink their database strategy. Learn how they architected a solution that would simplify scaling while keeping costs under control.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/how-axelera-ai-uses-digital-compute-in-memory-to-deliver-fast-and-energy-efficient-computer-vision-a-presentation-from-axelera-ai/
Bram Verhoef, Head of Machine Learning at Axelera AI, presents the “How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-efficient Computer Vision” tutorial at the May 2024 Embedded Vision Summit.
As artificial intelligence inference transitions from cloud environments to edge locations, computer vision applications achieve heightened responsiveness, reliability and privacy. This migration, however, introduces the challenge of operating within the stringent confines of resource constraints typical at the edge, including small form factors, low energy budgets and diminished memory and computational capacities. Axelera AI addresses these challenges through an innovative approach of performing digital computations within memory itself. This technique facilitates the realization of high-performance, energy-efficient and cost-effective computer vision capabilities at the thin and thick edge, extending the frontier of what is achievable with current technologies.
In this presentation, Verhoef unveils his company’s pioneering chip technology and demonstrates its capacity to deliver exceptional frames-per-second performance across a range of standard computer vision networks typical of applications in security, surveillance and the industrial sector. This shows that advanced computer vision can be accessible and efficient, even at the very edge of our technological ecosystem.
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsDianaGray10
Join us to learn how UiPath Apps can directly and easily interact with prebuilt connectors via Integration Service--including Salesforce, ServiceNow, Open GenAI, and more.
The best part is you can achieve this without building a custom workflow! Say goodbye to the hassle of using separate automations to call APIs. By seamlessly integrating within App Studio, you can now easily streamline your workflow, while gaining direct access to our Connector Catalog of popular applications.
We’ll discuss and demo the benefits of UiPath Apps and connectors including:
Creating a compelling user experience for any software, without the limitations of APIs.
Accelerating the app creation process, saving time and effort
Enjoying high-performance CRUD (create, read, update, delete) operations, for
seamless data management.
Speakers:
Russell Alfeche, Technology Leader, RPA at qBotic and UiPath MVP
Charlie Greenberg, host
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
AppSec PNW: Android and iOS Application Security with MobSFAjin Abraham
Mobile Security Framework - MobSF is a free and open source automated mobile application security testing environment designed to help security engineers, researchers, developers, and penetration testers to identify security vulnerabilities, malicious behaviours and privacy concerns in mobile applications using static and dynamic analysis. It supports all the popular mobile application binaries and source code formats built for Android and iOS devices. In addition to automated security assessment, it also offers an interactive testing environment to build and execute scenario based test/fuzz cases against the application.
This talk covers:
Using MobSF for static analysis of mobile applications.
Interactive dynamic security assessment of Android and iOS applications.
Solving Mobile app CTF challenges.
Reverse engineering and runtime analysis of Mobile malware.
How to shift left and integrate MobSF/mobsfscan SAST and DAST in your build pipeline.
Conversational agents, or chatbots, are increasingly used to access all sorts of services using natural language. While open-domain chatbots - like ChatGPT - can converse on any topic, task-oriented chatbots - the focus of this paper - are designed for specific tasks, like booking a flight, obtaining customer support, or setting an appointment. Like any other software, task-oriented chatbots need to be properly tested, usually by defining and executing test scenarios (i.e., sequences of user-chatbot interactions). However, there is currently a lack of methods to quantify the completeness and strength of such test scenarios, which can lead to low-quality tests, and hence to buggy chatbots.
To fill this gap, we propose adapting mutation testing (MuT) for task-oriented chatbots. To this end, we introduce a set of mutation operators that emulate faults in chatbot designs, an architecture that enables MuT on chatbots built using heterogeneous technologies, and a practical realisation as an Eclipse plugin. Moreover, we evaluate the applicability, effectiveness and efficiency of our approach on open-source chatbots, with promising results.
Dandelion Hashtable: beyond billion requests per second on a commodity serverAntonios Katsarakis
This slide deck presents DLHT, a concurrent in-memory hashtable. Despite efforts to optimize hashtables, that go as far as sacrificing core functionality, state-of-the-art designs still incur multiple memory accesses per request and block request processing in three cases. First, most hashtables block while waiting for data to be retrieved from memory. Second, open-addressing designs, which represent the current state-of-the-art, either cannot free index slots on deletes or must block all requests to do so. Third, index resizes block every request until all objects are copied to the new index. Defying folklore wisdom, DLHT forgoes open-addressing and adopts a fully-featured and memory-aware closed-addressing design based on bounded cache-line-chaining. This design offers lock-free index operations and deletes that free slots instantly, (2) completes most requests with a single memory access, (3) utilizes software prefetching to hide memory latencies, and (4) employs a novel non-blocking and parallel resizing. In a commodity server and a memory-resident workload, DLHT surpasses 1.6B requests per second and provides 3.5x (12x) the throughput of the state-of-the-art closed-addressing (open-addressing) resizable hashtable on Gets (Deletes).
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/temporal-event-neural-networks-a-more-efficient-alternative-to-the-transformer-a-presentation-from-brainchip/
Chris Jones, Director of Product Management at BrainChip , presents the “Temporal Event Neural Networks: A More Efficient Alternative to the Transformer” tutorial at the May 2024 Embedded Vision Summit.
The expansion of AI services necessitates enhanced computational capabilities on edge devices. Temporal Event Neural Networks (TENNs), developed by BrainChip, represent a novel and highly efficient state-space network. TENNs demonstrate exceptional proficiency in handling multi-dimensional streaming data, facilitating advancements in object detection, action recognition, speech enhancement and language model/sequence generation. Through the utilization of polynomial-based continuous convolutions, TENNs streamline models, expedite training processes and significantly diminish memory requirements, achieving notable reductions of up to 50x in parameters and 5,000x in energy consumption compared to prevailing methodologies like transformers.
Integration with BrainChip’s Akida neuromorphic hardware IP further enhances TENNs’ capabilities, enabling the realization of highly capable, portable and passively cooled edge devices. This presentation delves into the technical innovations underlying TENNs, presents real-world benchmarks, and elucidates how this cutting-edge approach is positioned to revolutionize edge AI across diverse applications.
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...Alex Pruden
Folding is a recent technique for building efficient recursive SNARKs. Several elegant folding protocols have been proposed, such as Nova, Supernova, Hypernova, Protostar, and others. However, all of them rely on an additively homomorphic commitment scheme based on discrete log, and are therefore not post-quantum secure. In this work we present LatticeFold, the first lattice-based folding protocol based on the Module SIS problem. This folding protocol naturally leads to an efficient recursive lattice-based SNARK and an efficient PCD scheme. LatticeFold supports folding low-degree relations, such as R1CS, as well as high-degree relations, such as CCS. The key challenge is to construct a secure folding protocol that works with the Ajtai commitment scheme. The difficulty, is ensuring that extracted witnesses are low norm through many rounds of folding. We present a novel technique using the sumcheck protocol to ensure that extracted witnesses are always low norm no matter how many rounds of folding are used. Our evaluation of the final proof system suggests that it is as performant as Hypernova, while providing post-quantum security.
Paper Link: https://eprint.iacr.org/2024/257
The Microsoft 365 Migration Tutorial For Beginner.pptxoperationspcvita
This presentation will help you understand the power of Microsoft 365. However, we have mentioned every productivity app included in Office 365. Additionally, we have suggested the migration situation related to Office 365 and how we can help you.
You can also read: https://www.systoolsgroup.com/updates/office-365-tenant-to-tenant-migration-step-by-step-complete-guide/
The Microsoft 365 Migration Tutorial For Beginner.pptx
ch:8CS112
1. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Chapter 8 Objects and Classes
1
2. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Grades
40% Final
20%Midterm
20% Lab
10%Quiz
5%Assignment
5%class participation
2
3. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Rules
Always attend class on time.
Being late 3 times will be considered absent
Phones always off/silent
Submit your assignment on the specific date or
you will lose marks.
3
4. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
OO Programming Concepts
Object-oriented programming (OOP)
involves programming using objects. An
object represents an entity in the real
world that can be distinctly identified. For
example, a student, a desk, a circle, a
button, and even a loan can all be
viewed as objects.
4
5. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
OO Programming Concepts
An object has a unique identity, state,
and behaviors. The state of an object
consists of a set of data fields (also known
as properties) with their current values.
The behavior(actions) of an object is
defined by a set of methods.
5
6. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Objects
6
An object has both a state and behavior. The
state defines the object, and the behavior
defines what the object does.
Class Name: Circle
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Data Fields:
radius is 10
Circle Object 2
Data Fields:
radius is 25
Circle Object 3
Data Fields:
radius is 125
A class template
Three objects of
the Circle class
7. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Classes
Classes are constructs that define objects
of the same type. A Java class uses
variables to define data fields and
methods to define behaviors. Additionally,
a class provides a special type of
methods, known as constructors, which
are invoked to construct objects from the
class.
7
8. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Classes 8
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}
Data field
Method
Constructors
9. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
UML Class Diagram
9
Circle
radius: double
Circle()
Circle(newRadius: double)
getArea(): double
circle1: Circle
radius = 1.0
Class name
Data fields
Constructors and
methods
circle2: Circle
radius = 25
circle3: Circle
radius = 125
UML Class Diagram
UML notation
for objects
10. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Example: Defining Classes and
Creating Objects
Objective: Demonstrate creating objects,
accessing data, and using methods.
10
11. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
11
12. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Output
12
13. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Example: Defining
Classes and Creating Objects
consider TV sets. Each TV is an object with states (current channel,current
volume level, power on or off) and behaviors (change channels, adjust volume,
turn on/off). You can use a class to model TV sets. The UML diagram for the
class is shown in
13
14. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
14
15. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
15
16. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Output
16
17. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Constructors
17
Constructors are a special kind of methods
that are invoked to construct objects.
Example:
• Circle() { *no-arg constructor
}
• Circle(double newRadius) {
radius = newRadius;
}
18. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Constructors, cont.
A constructor with no parameters is referred
to as a no-arg constructor.
· Constructors must have the same
name as the class itself.
Constructors do not have a return type—not
even void.
· Constructors are invoked using the new
operator when an object is created.
Constructors play the role of initializing
objects.
18
19. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Creating Objects Using Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
19
20. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Default Constructor
20
A class may be declared without constructors.
In this case, a no-arg constructor with an
empty body is implicitly declared in the class.
This constructor, called a default constructor,
is provided automatically only if no
constructors are explicitly declared in the
class.
21. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
To declare a reference variable, use the syntax:
ClassName objectRefVar;
Example:
Circle myCircle;
21
22. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Example:
Circle myCircle = new Circle();
22
Create an objectAssign object reference
23. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Accessing Objects
Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
23
24. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Trace Code 24
Circle myCircle = new Circle(5.0);
SCircle yourCircle = new Circle();
yourCircle.radius = 100;
Declare myCircle
no valuemyCircle
animation
25. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Trace Code, cont.
: Circle
radius: 5.0
25
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
no valuemyCircle
Create a circle
animation
26. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Trace Code, cont.
: Circle
radius: 5.0
26
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
reference valuemyCircle
Assign object
reference to myCircle
animation
27. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Trace Code, cont.
: Circle
radius: 5.0
27
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
reference valuemyCircle
no valueyourCircle
Declare yourCircle
animation
28. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Trace Code, cont.
: Circle
radius: 5.0
28
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
reference valuemyCircle
no valueyourCircle
: Circle
radius: 0.0Create a new
Circle object
animation
29. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Trace Code, cont.
: Circle
radius: 5.0
29
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
reference valuemyCircle
reference valueyourCircle
: Circle
radius: 1.0
Assign object
reference to yourCircle
animation
30. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Trace Code, cont.
: Circle
radius: 5.0
30
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
reference valuemyCircle
reference valueyourCircle
: Circle
radius: 100.0Change radius in
yourCircle
animation
31. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Caution
Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
to invoke a method in the Math class. Can you invoke
getArea() using Circle1.getArea()? The answer is no. All
the methods used before this chapter are static methods,
which are defined using the static keyword. However,
getArea() is non-static. It must be invoked from an object
using
objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).
More explanations will be given in the section on “Static
Variables, Constants, and Methods.”
31
32. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Reference Data Fields
The data fields can be of reference types. For
example, the following Student class contains a data
field name of the String type.
32
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value
false
char gender; // c has default value 'u0000'
}
33. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The null Value
If a data field of a reference type
does not reference any object, the
data field holds a special literal
value, null.
33
34. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Default Value for a Data Field
The default value of a data field is null for a
reference type,
0 for a numeric type,
false for a boolean type,
and 'u0000' for a char type.
However, Java assigns no default value to a local
variable inside a method.
34
35. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Default Value for a Data Field
35
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " +
student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
36. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Example
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
36
Compilation error: variables not
initialized
Java assigns no default value to a local variable
inside a method.
37. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Differences between Variables of
Primitive Data Types and Object Types
37
1Primitive type int i = 1 i
Object type Circle c c reference
Created using new Circle()
c: Circle
radius = 1
38. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Copying Variables of Primitive Data
Types and Object Types
38
i
Primitive type assignment i = j
Before:
1
j 2
i
After:
2
j 2
c1
Object type assignment c1 = c2
Before:
c2
c1
After:
c2
c1: Circle
radius = 5
C2: Circle
radius = 9
c1: Circle
radius = 5
C2: Circle
radius = 9
39. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Copying Variables of Primitive Data
Types and Object Types
39
i
Primitive type assignment i = j
Before:
1
j 2
i
After:
2
j 2
c1
Object typeassignment c1 = c2
Before:
c2
c1
After:
c2
c1:Circle
radius = 5
C2:Circle
radius = 9
c1:Circle
radius = 5
C2: Circle
radius = 9
40. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Garbage Collection
As shown in the previous figure, after the
assignment statement c1 = c2, c1 points to
the same object referenced by c2. The
object previously referenced by c1 is no
longer referenced. This object is known as
garbage. Garbage is automatically
collected by JVM.
40
41. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Garbage Collection, cont
TIP: If you know that an object is no
longer needed, you can explicitly assign
null to a reference variable for the
object. The JVM will automatically
collect the space if the object is not
referenced by any variable.
41
42. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Date Class
Java provides a system-independent
encapsulation of date and time in the
java.util.Date class. You can use the Date
class to create an instance for the current
date and time and use its toString method to
return the date and time as a string.
42
43. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
43
java.util.Date
+Date()
+Date(elapseTime:long)
+toString():String
+getTime():long
+setTime(elapseTime:long):void
ConstructsaDateobjectforthecurrenttime.
ConstructsaDateobjectforagiventimein
millisecondselapsedsinceJanuary1,1970,GMT.
Returnsastringrepresentingthedateandtime.
ReturnsthenumberofmillisecondssinceJanuary1,
1970,GMT.
Setsanewelapsetimeintheobject.
The+signindicates
publicmodifer
The Date Class
44. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Date Class Example
For example, the following code
java.util.Date date = new
java.util.Date();
System.out.println(date.toString());
displays a string like Sun Mar 09 13:50:19 EST
2003.
44
45. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Random Class
You have used Math.random() to obtain a random
double value between 0.0 and 1.0 (excluding 1.0). A
more useful random number generator is provided in
the java.util.Random class.
45
java.util.Random
+Random()
+Random(seed: long)
+nextInt(): int
+nextInt(n: int): int
+nextLong(): long
+nextDouble(): double
+nextFloat(): float
+nextBoolean(): boolean
Constructs a Random object with the current time as its seed.
Constructs a Random object with a specified seed.
Returns a random int value.
Returns a random int value between 0 and n (exclusive).
Returns a random long value.
Returns a random double value between 0.0 and 1.0 (exclusive).
Returns a random float value between 0.0F and 1.0F (exclusive).
Returns a random boolean value.
46. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Random Class Example
If two Random objects have the same seed, they will generate
identical sequences of numbers. For example, the following code
creates two Random objects with the same seed 3.
Random random1 = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(1000) + " ");
46
47. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Out Put
47
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
48. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Instance Variables, and Methods
48
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of
the class.
49. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Static Variables, Constants,
and Methods
Static variables are shared by all the
instances of the class.
Static methods are not tied to a specific
object.
Static constants are final variables shared by
all the instances of the class.
To declare static variables, constants, and
methods, use the static modifier.
49
50. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
50
51. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
51
Circle
radius: double
numberOfObjects: int
getNumberOfObjects(): int
+getArea(): double
1 radius
circle1
radius = 1
numberOfObjects = 2
instantiate
instantiate
Memory
2
5 radius
numberOfObjects
UML Notation:
+: public variables or methods
underline: static variables or methods
circle2
radius = 5
numberOfObjects = 2
After two Circle
objects were created,
numberOfObjects
is 2.
52. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Invoke a static method
Use ClassName.methodName(arguments) to
invoke a static method and
ClassName.- staticVariable to access a
static variable.
This improves readability, because the
user can easily recognize the static
method and data in the class.
52
53. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Visibility Modifiers and
Accessor/Mutator Methods
53
By default, the class, variable, or method can
be
accessed by any class in the same package.public
The class, data, or method is visible to any class in any
package.
private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
54. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
54
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.
public class C1 {
public int x;
int y;
private int z;
public void m1() {
}
void m2() {
}
private void m3() {
}
}
public class C2 {
void aMethod() {
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;
can invoke o.m1();
can invoke o.m2();
cannot invoke o.m3();
}
}
package p1; package p2;
public class C3 {
void aMethod() {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
can invoke o.m1();
cannot invoke o.m2();
cannot invoke o.m3();
}
}
class C1 {
...
}
public class C2 {
can access C1
}
package p1; package p2;
public class C3 {
cannot access C1;
can access C2;
}
55. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
NOTE
55
An object cannot access its private members, as shown in (b).
It is OK, however, if the object is declared in its own class, as
shown in (a).
public class Foo {
private boolean x;
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert());
}
private int convert(boolean b) {
return x ? 1 : -1;
}
}
(a) This is OK because object foo is used inside the Foo class
public class Test {
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert(foo.x));
}
}
(b) This is wrong because x and convert are private in Foo.
56. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Why Data Fields Should Be private?
To protect data.
To make class easy to maintain.
56
57. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Example of
Data Field Encapsulation
57
Circle3Circle3 RunRunTestCircle3TestCircle3
Circle
-radius: double
-numberOfObjects: int
+Circle()
+Circle(radius: double)
+getRadius(): double
+setRadius(radius: double): void
+getNumberOfObject(): int
+getArea(): double
The radius of this circle (default: 1.0).
The number of circle objects created.
Constructs a default circle object.
Constructs a circle object with the specified radius.
Returns the radius of this circle.
Sets a new radius for this circle.
Returns the number of circle objects created.
Returns the area of this circle.
The - sign indicates
private modifier
58. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Passing Objects to Methods
Passing by value for primitive type value (the value is
passed to the parameter)
Passing by value for reference type value (the value is the
reference to the object)
58
TestPassObjectTestPassObject RunRun
59. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Passing Objects to Methods, cont.
59
Space required for the
main method
int n: 5
myCircle:
Stack
Space required for the
printAreas method
int times: 5
Circle c:
reference
A circle
object
Heap
reference
Pass by value
(here the value is
the reference for
the object)
Pass by value (here
the value is 5)