The document provides an overview of classes and objects in Java. It discusses container classes versus definition classes, and gives examples of the Math and Turtle classes. It explains key concepts like abstraction, encapsulation, and the relationship between classes and objects. Specific examples like the Clock and BankAccount classes are used to illustrate concepts like instance variables, constructors, methods, visibility modifiers, and API documentation.
This document contains slides from a lecture on classes and objects in Java. It discusses key concepts like class abstraction, encapsulation, constructors, instance variables, methods and scope. Specifically, it uses examples of a Clock and Turtle class to illustrate how to define the internal state and behaviors of an object using a class. The relationship between classes and objects is analogous to blueprints and real objects built from them. Methods can access and modify an object's internal state.
This document contains slides from a lecture on classes and objects in Java. It discusses key concepts like class abstraction, encapsulation, instance variables, constructors, methods, visibility modifiers, and more. An example class discussed is Clock, which represents a 12-hour clock and defines its internal state (hours, minutes, seconds) and interface (get/set time methods).
Classes allow the creation of user-defined data types through the grouping of related properties and behaviors. They contain members like variables and methods that can be declared as private, protected, public or static. Constructors initialize new class objects, while finalizers run before objects are destroyed. The toString method returns a string representation of an object. Abstract data types specify logical properties without implementation details. An example program designs classes for a candy machine application that displays products, accepts selections and payments, and dispenses items.
Here is the implementation of the DayType class with the required operations:
[CODE]
#include <iostream>
using namespace std;
class DayType {
private:
string day;
public:
DayType(string d="Sun") {
day = d;
}
void setDay(string d) {
day = d;
}
void printDay() {
cout << day << endl;
}
string returnDay() {
return day;
}
string nextDay() {
if(day == "Sat")
return "Sun";
else {
int index = 0;
if(day == "Sun")
index = 0;
This chapter discusses user-defined classes and abstract data types (ADTs) in Java. It covers defining classes with private, protected, public, and static members. Constructors and finalizers are examined. The toString method is explored. Abstract data types are introduced as data types that specify logical properties without implementation details. An example candy machine problem is presented to demonstrate defining classes for a non-GUI and GUI application to model a candy machine with items for sale, a cash register, dispenser, and other components.
Programming II hiding, and replacing members, Serialization, Generics, Linq ExceptionType
enum You will implement this enum in Visual Studio. There are seven members: Assignment 4 -
Implementing a Banking Application Due: See course shell for due date and time Check with
you professor to see if you are permitted to work as a group. The members are self-explanatory.
AccountType enum You will implement this enum in Visual Studio. There are three members:
The application is by far the most complex system that you have attempted so far. It consists of
eleven classes, two structs, one interface and two enums coupled in varying degrees of tightness.
The Bank class is the main driver of the application. It has collection of Accounts and Person
that is initialize appropriately in the static constructor. You will implement the entire system in
Visual Studio. A short description of each type with their members is given below. You are
advised to implement each type in the order that they are described. No method should have a
Console. WriteLine() unless you are explicitly told to output something on the console. Each
type must be in separate files.
Assignment 4, Winter 2022 Assignment 4, Winter 2022 hiding, and replacing members,
Serialization, Generics, ling Uses - Inheritance, Interfaces, Exceptions, EventHandlers,
Collections Operator overloading, Utils class hiding, and replacing members, Serialization,
Generics, Ling [The implementation for this class is given in the appendix. Create a class called
UtIs and copy and 1. Time - this public class variable is of type Day Time. It adds a random
value to the internal field_time and then returns it. past the statements into the appropriate part of
the file] 2. Now - this public class variable is of type Day Time. It adds zero to the internal
field_time You will implement the Utils class in Visual Studio. This class is comprised of three
fields and and then returns it. provides two static properties. It simulates the passage of time.
Each time the Time property is Methods: accessed, it increases the internal field by a random
amount. It is used to time stamped all banking There are no explicitly defined methods. You do
not have to code this class. Just copy the code statements from the appendix of this A short
description of each dass member is given below: document. Properties: There are three
properties. 1. _time - this private class variable is of type DayTime that store the time of this
object. It is initialized (with argument 1_648_600_800 ) at declaration. It is mutated (changed)
whenever either of the properties is accessed. 2. random - this private class variable is of type
Random storing the time of this object. It is initialized (with argument 1_848_800_800) at
declaration. It is mutated (changed) whenever elther of the properties is accessed. 3.
ACCOUNT_TYPE - this private class variable is of type Dictionary. It serves as a lookup table
to match an account type with a particular prefix, It is i.
The document provides an overview of defining custom classes in Java, including how to return objects from methods, use the 'this' keyword, define overloaded methods and constructors, create class and static methods, implement parameter passing, organize classes into packages, and document classes with Javadoc comments. Key concepts like inheritance, polymorphism, and abstraction are not discussed. The chapter aims to describe the basics of defining custom classes in Java.
This document contains slides from a lecture on classes and objects in Java. It discusses key concepts like class abstraction, encapsulation, constructors, instance variables, methods and scope. Specifically, it uses examples of a Clock and Turtle class to illustrate how to define the internal state and behaviors of an object using a class. The relationship between classes and objects is analogous to blueprints and real objects built from them. Methods can access and modify an object's internal state.
This document contains slides from a lecture on classes and objects in Java. It discusses key concepts like class abstraction, encapsulation, instance variables, constructors, methods, visibility modifiers, and more. An example class discussed is Clock, which represents a 12-hour clock and defines its internal state (hours, minutes, seconds) and interface (get/set time methods).
Classes allow the creation of user-defined data types through the grouping of related properties and behaviors. They contain members like variables and methods that can be declared as private, protected, public or static. Constructors initialize new class objects, while finalizers run before objects are destroyed. The toString method returns a string representation of an object. Abstract data types specify logical properties without implementation details. An example program designs classes for a candy machine application that displays products, accepts selections and payments, and dispenses items.
Here is the implementation of the DayType class with the required operations:
[CODE]
#include <iostream>
using namespace std;
class DayType {
private:
string day;
public:
DayType(string d="Sun") {
day = d;
}
void setDay(string d) {
day = d;
}
void printDay() {
cout << day << endl;
}
string returnDay() {
return day;
}
string nextDay() {
if(day == "Sat")
return "Sun";
else {
int index = 0;
if(day == "Sun")
index = 0;
This chapter discusses user-defined classes and abstract data types (ADTs) in Java. It covers defining classes with private, protected, public, and static members. Constructors and finalizers are examined. The toString method is explored. Abstract data types are introduced as data types that specify logical properties without implementation details. An example candy machine problem is presented to demonstrate defining classes for a non-GUI and GUI application to model a candy machine with items for sale, a cash register, dispenser, and other components.
Programming II hiding, and replacing members, Serialization, Generics, Linq ExceptionType
enum You will implement this enum in Visual Studio. There are seven members: Assignment 4 -
Implementing a Banking Application Due: See course shell for due date and time Check with
you professor to see if you are permitted to work as a group. The members are self-explanatory.
AccountType enum You will implement this enum in Visual Studio. There are three members:
The application is by far the most complex system that you have attempted so far. It consists of
eleven classes, two structs, one interface and two enums coupled in varying degrees of tightness.
The Bank class is the main driver of the application. It has collection of Accounts and Person
that is initialize appropriately in the static constructor. You will implement the entire system in
Visual Studio. A short description of each type with their members is given below. You are
advised to implement each type in the order that they are described. No method should have a
Console. WriteLine() unless you are explicitly told to output something on the console. Each
type must be in separate files.
Assignment 4, Winter 2022 Assignment 4, Winter 2022 hiding, and replacing members,
Serialization, Generics, ling Uses - Inheritance, Interfaces, Exceptions, EventHandlers,
Collections Operator overloading, Utils class hiding, and replacing members, Serialization,
Generics, Ling [The implementation for this class is given in the appendix. Create a class called
UtIs and copy and 1. Time - this public class variable is of type Day Time. It adds a random
value to the internal field_time and then returns it. past the statements into the appropriate part of
the file] 2. Now - this public class variable is of type Day Time. It adds zero to the internal
field_time You will implement the Utils class in Visual Studio. This class is comprised of three
fields and and then returns it. provides two static properties. It simulates the passage of time.
Each time the Time property is Methods: accessed, it increases the internal field by a random
amount. It is used to time stamped all banking There are no explicitly defined methods. You do
not have to code this class. Just copy the code statements from the appendix of this A short
description of each dass member is given below: document. Properties: There are three
properties. 1. _time - this private class variable is of type DayTime that store the time of this
object. It is initialized (with argument 1_648_600_800 ) at declaration. It is mutated (changed)
whenever either of the properties is accessed. 2. random - this private class variable is of type
Random storing the time of this object. It is initialized (with argument 1_848_800_800) at
declaration. It is mutated (changed) whenever elther of the properties is accessed. 3.
ACCOUNT_TYPE - this private class variable is of type Dictionary. It serves as a lookup table
to match an account type with a particular prefix, It is i.
The document provides an overview of defining custom classes in Java, including how to return objects from methods, use the 'this' keyword, define overloaded methods and constructors, create class and static methods, implement parameter passing, organize classes into packages, and document classes with Javadoc comments. Key concepts like inheritance, polymorphism, and abstraction are not discussed. The chapter aims to describe the basics of defining custom classes in Java.
This document discusses defining custom classes in Java. It covers topics like returning objects from methods, using the "this" keyword, overloaded methods and constructors, class methods and variables, and organizing classes into packages. Key points include how objects are passed by value to method parameters rather than by reference, and how to document classes using Javadoc comments.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
The document discusses defining classes and objects in Java. It covers defining simple classes, class elements like fields and methods, constructors, properties, static members, and using classes by creating instances and calling methods. Key points include classes define the structure of objects, constructors initialize object state, properties encapsulate fields, and static members are associated with a class not individual objects.
The document discusses classes, methods, and objects in C#. It explains that classes define methods and properties, and methods perform actions and can take parameters and return values. It provides examples of commonly used methods in classes like Console, Math, and Random. It also discusses how to define classes with data members and methods, and how to create objects from classes which allows calling instance methods on those objects. Classes serve both as program modules containing static methods and data, and as blueprints for generating objects with their own state and behavior.
The document describes object-oriented programming concepts like classes, objects, encapsulation, and properties. It provides code examples of a Time class that encapsulates time data and provides methods to work with it. The Time class uses properties to safely access private member variables for hour, minute and second. Constructors are demonstrated that initialize Time objects with different parameters.
The Ring programming language version 1.2 book - Part 78 of 84Mahmoud Samir Fayed
Ring allows defining classes with attributes and methods. When a new object is created:
1. The class region code is executed to initialize the object's attributes.
2. Methods are collected from the class and parent classes to be called on the object.
3. Attributes can be accessed directly or via getter/setter methods, which are called automatically.
Global names are searched when defining attributes to allow dynamic attribute definition based on global state. However, this could cause conflicts that the programmer must avoid, such as by prepending names with $ or self..
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 object-oriented programming concepts in Java including objects, classes, constructors, inheritance, polymorphism, and access modifiers.
The key points are:
1) An object represents an entity with a unique identity, state, and behaviors. A class defines common properties and behaviors of objects.
2) Constructors initialize new objects, while methods define object behaviors. Inheritance allows subclasses to inherit properties and behaviors from parent classes.
3) Access modifiers like public, private, and protected control the visibility and accessibility of classes, variables, and methods. Final and abstract modifiers are also used to restrict or require subclassing.
The Ring programming language version 1.9 book - Part 98 of 210Mahmoud Samir Fayed
Ring provides constructor methods when creating new objects. When a new object is created:
1. Memory is allocated for the object's attributes
2. The current scope is changed to the new object
3. Code in the class region is executed to initialize the object
4. Attributes added in the class region are dynamic
The document discusses C++ functions and classes. It provides examples of void and returning value functions, including a program to convert Fahrenheit to Celsius using a returning value function. It also discusses basics of classes, including defining a class with data members and member functions, and creating an object of that class to access its members.
This document discusses methods in Java. It explains that a method declaration specifies the code that is executed when the method is called. Methods can take parameters as input and can return a value. The document provides an example of a Rectangle class with methods to calculate the area and perimeter of a rectangle. It includes the class definition with these methods and shows how to create Rectangle objects, call the methods on them, and print the results.
The document discusses the structure of Java classes. A class describes a set of objects through fields, constructors, and methods. Fields hold an object's data, constructors create new objects, and methods describe actions objects can perform. A class can also contain static data and methods that are not part of individual objects. Methods define the behavior of a class using parameters, return types, and local variables. Objects communicate by sending messages to each other's methods.
This document discusses methods and constructors in Java. It defines methods as tasks that can take parameters and return values. Constructors are used to initialize new objects and are called when a new object is created using the new keyword. The document provides an example Rectangle class with methods to calculate area and perimeter, and a constructor to initialize length and width variables. It also shows calling these methods on Rectangle objects after creating them with the constructor.
Java Foundations: Data Types and Type ConversionSvetlin Nakov
Learn how to use data types and variables in Java, how variables are stored in the memory and how to convert from one data type to another.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-data-types-and-variables
The document defines classes and methods in Java.
It discusses:
1) The syntax for defining a class with modifiers, data declarations, and method definitions.
2) How a class can contain data declarations and method declarations to store information and perform behaviors.
3) The structure of a method including the header, parameters, and body.
4) How to define constructors, static methods, and overload methods in a class.
1) The document discusses user-defined classes in Java, including defining classes with modifiers, data declarations, and method definitions. It provides examples of class definitions with private instance variables and public methods.
2) It describes the syntax for defining methods, including the method header with return type and parameters. The document explains value-returning methods, void methods, and use of return statements.
3) The document shows an example class definition for a Rectangle with constructor, getter, and calculateArea methods to demonstrate object instantiation and method calls.
This document provides an introduction to creating and using classes in C#. Key points covered include defining classes with fields, methods, and constructors; using accessibility modifiers like public and private; calling methods and using the this keyword; creating static methods; and using listboxes, comboboxes, and events for selection changes. Examples are provided for defining classes, constructors, static and instance methods, and populating and accessing selection properties of list and combo boxes.
This document provides an overview of object-oriented programming concepts in Java, including classes, objects, variables, methods, constructors, abstraction, encapsulation, inheritance, and polymorphism. It defines classes and objects, and describes how classes act as blueprints for objects. It explains the syntax for defining classes and class members like variables and methods. It also covers method overloading, different types of methods, and how constructors are used to initialize objects. The document concludes with brief explanations of abstraction, encapsulation, inheritance, and polymorphism as fundamental principles of object-oriented design.
1. The document discusses deterministic finite automata (DFAs) and nondeterministic finite automata (NFAs). DFAs have a single transition function, while NFAs have a transition function that can map a state-symbol pair to multiple possible next states.
2. Examples are given of DFAs and NFAs that accept certain languages over various alphabets. The DFA examples use transition diagrams to represent the transition functions, while the NFA examples explicitly define the transition functions.
3. Key properties of DFAs and NFAs are summarized, including their definitions as 5-tuples and how languages are accepted by looking for paths from the starting to a final state.
This document discusses probabilistic models for classification tasks. It describes generative models that model the joint probability of classes and features to calculate class posterior probabilities using Bayes' rule. Generative models make assumptions like conditional independence of features. Discriminative models directly model the posterior probability of classes given features and make fewer assumptions. Maximum likelihood estimation techniques are discussed for estimating the parameters of generative models like naive Bayes and logistic regression. The document also covers decision theory and different loss functions used for classification.
This document discusses defining custom classes in Java. It covers topics like returning objects from methods, using the "this" keyword, overloaded methods and constructors, class methods and variables, and organizing classes into packages. Key points include how objects are passed by value to method parameters rather than by reference, and how to document classes using Javadoc comments.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
The document discusses defining classes and objects in Java. It covers defining simple classes, class elements like fields and methods, constructors, properties, static members, and using classes by creating instances and calling methods. Key points include classes define the structure of objects, constructors initialize object state, properties encapsulate fields, and static members are associated with a class not individual objects.
The document discusses classes, methods, and objects in C#. It explains that classes define methods and properties, and methods perform actions and can take parameters and return values. It provides examples of commonly used methods in classes like Console, Math, and Random. It also discusses how to define classes with data members and methods, and how to create objects from classes which allows calling instance methods on those objects. Classes serve both as program modules containing static methods and data, and as blueprints for generating objects with their own state and behavior.
The document describes object-oriented programming concepts like classes, objects, encapsulation, and properties. It provides code examples of a Time class that encapsulates time data and provides methods to work with it. The Time class uses properties to safely access private member variables for hour, minute and second. Constructors are demonstrated that initialize Time objects with different parameters.
The Ring programming language version 1.2 book - Part 78 of 84Mahmoud Samir Fayed
Ring allows defining classes with attributes and methods. When a new object is created:
1. The class region code is executed to initialize the object's attributes.
2. Methods are collected from the class and parent classes to be called on the object.
3. Attributes can be accessed directly or via getter/setter methods, which are called automatically.
Global names are searched when defining attributes to allow dynamic attribute definition based on global state. However, this could cause conflicts that the programmer must avoid, such as by prepending names with $ or self..
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 object-oriented programming concepts in Java including objects, classes, constructors, inheritance, polymorphism, and access modifiers.
The key points are:
1) An object represents an entity with a unique identity, state, and behaviors. A class defines common properties and behaviors of objects.
2) Constructors initialize new objects, while methods define object behaviors. Inheritance allows subclasses to inherit properties and behaviors from parent classes.
3) Access modifiers like public, private, and protected control the visibility and accessibility of classes, variables, and methods. Final and abstract modifiers are also used to restrict or require subclassing.
The Ring programming language version 1.9 book - Part 98 of 210Mahmoud Samir Fayed
Ring provides constructor methods when creating new objects. When a new object is created:
1. Memory is allocated for the object's attributes
2. The current scope is changed to the new object
3. Code in the class region is executed to initialize the object
4. Attributes added in the class region are dynamic
The document discusses C++ functions and classes. It provides examples of void and returning value functions, including a program to convert Fahrenheit to Celsius using a returning value function. It also discusses basics of classes, including defining a class with data members and member functions, and creating an object of that class to access its members.
This document discusses methods in Java. It explains that a method declaration specifies the code that is executed when the method is called. Methods can take parameters as input and can return a value. The document provides an example of a Rectangle class with methods to calculate the area and perimeter of a rectangle. It includes the class definition with these methods and shows how to create Rectangle objects, call the methods on them, and print the results.
The document discusses the structure of Java classes. A class describes a set of objects through fields, constructors, and methods. Fields hold an object's data, constructors create new objects, and methods describe actions objects can perform. A class can also contain static data and methods that are not part of individual objects. Methods define the behavior of a class using parameters, return types, and local variables. Objects communicate by sending messages to each other's methods.
This document discusses methods and constructors in Java. It defines methods as tasks that can take parameters and return values. Constructors are used to initialize new objects and are called when a new object is created using the new keyword. The document provides an example Rectangle class with methods to calculate area and perimeter, and a constructor to initialize length and width variables. It also shows calling these methods on Rectangle objects after creating them with the constructor.
Java Foundations: Data Types and Type ConversionSvetlin Nakov
Learn how to use data types and variables in Java, how variables are stored in the memory and how to convert from one data type to another.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-data-types-and-variables
The document defines classes and methods in Java.
It discusses:
1) The syntax for defining a class with modifiers, data declarations, and method definitions.
2) How a class can contain data declarations and method declarations to store information and perform behaviors.
3) The structure of a method including the header, parameters, and body.
4) How to define constructors, static methods, and overload methods in a class.
1) The document discusses user-defined classes in Java, including defining classes with modifiers, data declarations, and method definitions. It provides examples of class definitions with private instance variables and public methods.
2) It describes the syntax for defining methods, including the method header with return type and parameters. The document explains value-returning methods, void methods, and use of return statements.
3) The document shows an example class definition for a Rectangle with constructor, getter, and calculateArea methods to demonstrate object instantiation and method calls.
This document provides an introduction to creating and using classes in C#. Key points covered include defining classes with fields, methods, and constructors; using accessibility modifiers like public and private; calling methods and using the this keyword; creating static methods; and using listboxes, comboboxes, and events for selection changes. Examples are provided for defining classes, constructors, static and instance methods, and populating and accessing selection properties of list and combo boxes.
This document provides an overview of object-oriented programming concepts in Java, including classes, objects, variables, methods, constructors, abstraction, encapsulation, inheritance, and polymorphism. It defines classes and objects, and describes how classes act as blueprints for objects. It explains the syntax for defining classes and class members like variables and methods. It also covers method overloading, different types of methods, and how constructors are used to initialize objects. The document concludes with brief explanations of abstraction, encapsulation, inheritance, and polymorphism as fundamental principles of object-oriented design.
1. The document discusses deterministic finite automata (DFAs) and nondeterministic finite automata (NFAs). DFAs have a single transition function, while NFAs have a transition function that can map a state-symbol pair to multiple possible next states.
2. Examples are given of DFAs and NFAs that accept certain languages over various alphabets. The DFA examples use transition diagrams to represent the transition functions, while the NFA examples explicitly define the transition functions.
3. Key properties of DFAs and NFAs are summarized, including their definitions as 5-tuples and how languages are accepted by looking for paths from the starting to a final state.
This document discusses probabilistic models for classification tasks. It describes generative models that model the joint probability of classes and features to calculate class posterior probabilities using Bayes' rule. Generative models make assumptions like conditional independence of features. Discriminative models directly model the posterior probability of classes given features and make fewer assumptions. Maximum likelihood estimation techniques are discussed for estimating the parameters of generative models like naive Bayes and logistic regression. The document also covers decision theory and different loss functions used for classification.
The document discusses memory management techniques. It begins by explaining logical vs physical address spaces and the need for memory protection when multiple processes reside in memory. It then covers various memory allocation schemes like contiguous allocation, paging, and segmentation. Paging divides memory into fixed-sized frames and logical memory into pages. Address translation uses a page table to map logical to physical addresses. Hierarchical paging is introduced to reduce the size of large page tables.
The document discusses greedy algorithms and their use for optimization problems. It provides examples of using greedy approaches to solve scheduling and knapsack problems. Specifically, it describes how a greedy algorithm works by making locally optimal choices at each step in hopes of reaching a globally optimal solution. While greedy algorithms do not always find the true optimal, they often provide good approximations. The document also proves that certain greedy strategies, such as always selecting the item with the highest value to weight ratio for the knapsack problem, will find the true optimal solution.
The document discusses memory management techniques used in operating systems, including virtual memory. It explains that virtual memory allows the operating system to allocate more memory to processes than is physically available by swapping unused memory pages to disk as needed. This is done using page tables that map virtual addresses to physical addresses, with pages as the unit of mapping. The memory management unit in the CPU handles translating virtual addresses to physical addresses transparently to processes.
This document summarizes chapter 5 from the textbook "Operating System Concepts - 9th Edition" which covers process synchronization. It introduces the critical section problem where multiple processes need orderly access to shared resources. Peterson's algorithm and solutions using locks, mutexes, and semaphores are presented. These synchronization methods use atomic instructions to safely coordinate access to critical sections and ensure processes follow rules of mutual exclusion, progress, and bounded waiting.
This document summarizes a lecture on standard combinational modules. It discusses representation of numbers using 2's complement and 1's complement, and types of adders including half adders, full adders, ripple-carry adders, carry-lookahead adders, and prefix adders. It provides examples of addition and subtraction using each representation. It also briefly discusses comparators for equality and less than operations.
This document provides an overview of memory management techniques in operating systems, including swapping, contiguous allocation, segmentation, and paging. It discusses how logical and physical addresses are mapped and protected through the use of base and limit registers, and how context switch time can be impacted by swapping processes in and out of memory. Modern operating systems commonly use paging instead of swapping to manage memory.
The document discusses control unit design, including hardwired and microprogrammed approaches. It provides terminology for microprogrammed control, describing components like the control memory, sequencer, and microinstructions. It then covers the functions of the control unit like fetch cycles, instruction interpretation and execution. Details are given on instruction control transfer, program control transfer, and implementation methods for hardwired control logic like sequence counters and state tables. Microprogrammed control is more flexible but hardwired control can provide better performance.
An arithmetic logic unit (ALU) performs arithmetic and logic operations and is a fundamental building block of the central processing unit (CPU) of a computer. Even the simplest microprocessors contain an ALU for purposes such as maintaining timers. The ALU is a combinational logic circuit that can be implemented as a simple ALU that performs basic operations or a more complex ALU with additional functionality like zero and overflow outputs. The document discusses designing and testing an ALU, including examples of simple and enhanced ALU implementations.
This document discusses various topics related to air pollution and the atmosphere. It begins by defining greenhouse gases and their impact on global climate change, including consequences for sea levels, agriculture, and marine food. Next, it covers the structure of the atmosphere and composition of the troposphere. The document then discusses the greenhouse effect in more detail, and effects of global warming such as rising temperatures, sea levels, and impacts on agriculture and marine food. It concludes with methods for controlling global warming, such as reducing waste and emissions and using energy-efficient products.
The document discusses memory hierarchy and virtual memory. It summarizes:
- Memory hierarchy organizes memory into different levels from fastest and most expensive (cache/registers) to slowest and least expensive (magnetic disk). This is done to obtain the highest possible access speed while minimizing total cost.
- Virtual memory allows the memory address space to be larger than actual physical memory using memory mapping and paging. It gives the illusion of a larger memory through mapping of virtual addresses to physical addresses.
1. Computer memory is organized in a hierarchy from fast but small cache memory to slower but larger archival storage. Cache memory uses the locality principle to improve performance by keeping frequently used data close to the CPU.
2. There are different techniques for mapping memory addresses to cache locations including direct mapping, set associative mapping, and fully associative mapping. Direct mapping uses the low-order address bits to determine the cache slot while set associative mapping distributes blocks across multiple slots in a set.
3. Cache performance is measured by hit ratio, miss ratio, and mean access time. With a high hit ratio, the mean access time approaches the fast cache access time. Cache maintenance policies like write-back and
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
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
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.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
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.
2. Container vs. Definition classes
Generally, classes can be used for two
purposes:
Container classes:
a collection of static methods that are not
bound to any particular object (e.g., the main()
method).
These static methods usually have something in
common
Definition classes:
These classes define new objects, in a way that
we will soon see.
3. Container vs. Definition Classes -
Example
The Math class is an example of the first kind. It is a
container for math utility methods: Math.sqrt(),
Math.abs(), Math.max(), ...
The class Turtle is an example of the second kind. It
defines a new type of objects, Turtle objects.
We will now focus on the second kind.
4. Class Abstraction
The most important stage in writing a class is to get an
abstraction of the class done first.
What does an object of this type represent?
What is its interface?
What is its internal state?
This means you have to know what should be the internal
state (variables) and also the behavior/interface
(methods) of the class before you start to write you class
code.
5. Objects and Classes
The relationship between Classes and Objects can be seen as
the relationship between a blueprint/model and the the
actual object built from it.
Example: Blueprint of a house (class) and the house (object)
The class defines:
The type of data that will be held in an object
The code for the methods of the object
In order to use a class you must instantiate an object from it.
This corresponds to building the house from the blueprint.
There may be many objects from a single class
6. Turtle Class Abstraction
A Turtle represents a creature moving on the screen
with a pen attached to its tail
The internal state of a Turtle includes:
Location on screen; direction of movement; tail up/down
The interface of a Turtle is:
Turtle();
void moveForward(double units);
void moveBackward(double units);
void turnLeft(double degrees);
// …
7. Encapsulation
The internal state of an object is not directly accessible to
other parts of the program
Other parts of the program can only access the object
using its interface
We say that the state is
encapsulated or hidden
This gives modularity
to the program
moveForward()
turnRight()
.
.
.
.
.
.
•tailDown
•x,y
•direction
8. Clock Class Abstraction
A Clock represents a 12-hour clock
Its internal state includes: hour, minute, second
Its interface allows telling the clock that a second has
elapsed, and querying the clock for the time:
Clock(int hours, int minutes, int seconds)
int getSeconds()
void secondElapsed()
int getMinutes()
int getHours()
...
9. Using a Clock class
Clock newYorkTime = new Clock(12,59,59);
for (int j = 0; j < 3; j++)
newYorkTime.secondElapsed();
System.out.println(newYorkTime.getHours() +
“:” + newYorkTime.getMinutes() +
“:” + newYorkTime.getSeconds());
10. Structure of the Clock class
The private modifier specifies an identifier that is only visible
within the class. Usually used for fields.
The public modifier specifies an identifier that is accessible to all
other classes. Usually used for methods.
public class Clock {
private int hours, minutes, seconds;
public Clock(int h, int m, int s){ … }
public void secondElapsed() { … }
public int getHours() { … }
public int getMinutes() { … }
public int getSeconds() { … }
}
11. Lesson 4 – Classes & Objects
UNIT D2 - CLASS ELEMENTS
12. Instance Variables
Recall that a class must define the state of an object and
its behavior.
We declare state variables (variables that hold the state of
the object) in a similar way to that of regular variables,
only they appear outside methods, inside the class.
State variables are also called instance variables or fields.
Roughly speaking, the private modifier means that the
variables are not part of the object’s interface.
public class Clock {
private int hours, minutes, seconds;
// …
}
13. Constructors
Objects must be initialized before they can be used.
We must specify what is the initial state of the object
before we can use it.
Space for holding the object state data is only allocated
when the object is constructed.
We specify the way an object is initialized using a
constructor, which is a special method which is invoked
every time we create a new object
The name of the constructor is always identical to the
class name
15. Clock constructor invoked
public class Clock {
private int hours, minutes,seconds;
public Clock(int h, int m, int s){
hours = h;
minutes = m;
seconds = s;
}
// …
C:
10
45
0
Clock c;
c = new Clock(10,45,0);
hours:
Minutes:
Seconds:
16. Methods
To make the date object useful, we must provide methods
that define its behavior.
We declare methods in a similar way to the way the
method main was declared.
Only there’s a big difference:
the main method was static, which
means it wasn’t bound to a specific
object
we want to declare instance methods,
which operate on a specific instance of
an object
18. Return Types
Methods may return values
The return type of a method indicates the type of value that
the method sends back to the calling client
The return-type of getHours() is int. When a client ask
for the hours read of a clock it gets the answer as an int
value.
A method that does not return a value (such as
secondElapsed()) has a void return type
The return statement specifies the value that should be
returned, which must conform with the return type of the
method.
19. Clock accessor methods
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
20. Method Context
The getHours() and secondElapsed() methods are
instance methods, which means they act on a particular
instance of the class
They cannot be invoked “out of the blue”. They must act on a
particular object:
An instance method is executed in the context of the
object it acts upon.
Clock c = new Clock(1,2,3);
getHours(); // Error!! of which clock?
c.getHours(); // will return 1
21. ClockTest example
public class ClockTest {
public static void main(String[] args) {
Clock swatch = new Clock(12,59,59);
Clock seiko = new Clock(12,59,59);
System.out.println(swatch.getHours()); // 12
System.out.println(seiko.getHours()); // 12
swatch.secondElapsed();
System.out.println(swatch.getHours()); // 1
System.out.println(seiko.getHours()); // 12
}
}
22. Method Parameters
A method can be defined to accept zero or more
parameters
Each parameter in the parameter list is defined by its type
and name
The parameters in the method definition are called formal
parameters
The values passed to a method when it is invoked are
called actual parameters
The name of the method together with the list of its
formal parameters is called the signature of the method
public void setTime(int h, int m, int s)
23. Method setTime()
public void setTime(int h, int m, int s){
if ((s >= 0) && (s < 60) &&
(m >= 0) && (m < 60) &&
(h > 0) && (h <= 12)) {
hours = h;
minutes = m;
seconds = s;
}
// no effect if input is illegal
}
25. Variable Scope
Variables may be declared in:
Class – state variables
Method/constructor – local variables (and parameters)
Inner block of a method – also local variables
A variable is recognized throughout the block in which it was
defined. This is called the scope of the variable.
Local variables are allocated when the method is entered and
freed when the method exits.
The same name may be used in different scopes, and refer to
totally different things
If the same name is used in an outer and inner scope, then
the inner scope definition “hides” the outer one.
26. The this reference
When appearing inside an instance method, the this
keyword denotes a reference to the object that the
method is acting upon.
The following are equivalent:
public int getHours() {
return hours;
}
public int getHours() {
return this.hours;
}
27. Using same names for parameters
and fields
It is usually bad practice to use the same name for a state
variable and a local variable or parameter.
Exception: parameters that correspond exactly to fields
public void setTime(int hours,
int minutes,
int seconds) {
if ((seconds >= 0) && (seconds < 60) &&
(minutes >= 0) && (minutes < 60) &&
(hours > 0) && (hours <= 12)) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
// no effect if input is illegal
}
28. Passing Parameters
When a parameter is passed, a copy of the value is made
and assigned to the formal parameter:
Clock beritling = new Clock(1,2,3);
int lunchHour = 12;
breitling.setTime(lunchHour,32,14);
hours = lunchHour
minutes = 32
seconds = 14
29. Parameters are passed by value
Clock c = new Clock(1,2,3);
int a= 7;
c.funnyGetHour(a); // still 7!!
class Clock {
// …
public void funnyGetHour(int h){
h = hours;
}
}
30. Passing Object parameters
When an Object is a parameter, only the reference is
passed by value. The parameter now is an alias of the
object.
class XX {
// …
public void setMidnight(Clock c) {
c.setTime(12,0,0);
}
class YY {
// …
XX x = new XX();
Clock myClock = new Clock(1,2,3);
x.setMidnight(myClock); // 12:0:0
31. Example: A Bank Account Object
public BankAccount(long accountNumber)
public void deposit(double amount)
public void withdraw(double amount)
public double getBalance()
public void transfer(double amount,
BankAccount targetAccount)
BankAccount
32. Bank Account - example
public class BankAccount {
private long accountNumber;
private double balance;
public BankAccount(long accountNumber){
this.accountNumber = accountNumber;
balance = 0;
}
public double getBalance() {
return balance;
}
// continued in the next slide...
}
33. Bank Account - example
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
public void transfer(double amount,
BankAccount targetAccount){
withdraw(amount);
targetAccount.deposit(amount);
}
34. Bank Account – usage example
BankAccount aliceAcc = new BankAccount(1398723);
BankAccount bobAcc = new BankAccount(1978394);
aliceAcc.deposit(900);
aliceAcc.transfer(700,bobAcc);
// Alice’s balance = 200 ; Bob’s balance = 700
35. Constructor and Method
Overloading
A class can define several constructors -- several ways to
initialize an instance of this class
These constructors differ by the number and/or type of
parameters they get.
When we construct an object, the compiler decides which
constructor to invoke according to the number and types of
the actual arguments
A constructor with no parameters is called the default
constructor
Different methods can also use the same name as long as
they differ in the number or type of parameters.
When we invoke a method, the compiler decides which
method to invoke according to the number and types of the
actual arguments
36. Constructor Overloading example
public Clock(int h, int m, int s){
hours = h;
minutes = m;
seconds = s;
}
public Clock(int h) {
this(h, 0 ,0);
}
public Clock() {
this(12);
}
38. Visibility Modifiers
We accomplish encapsulation through the appropriate use
of visibility modifiers
Visibility modifiers specify which parts of the program may
see and use any particular class/method/field
Information hiding is good!
A modifier is a Java reserved word that specifies particular
characteristics of a programming construct
We've used the modifier final to define a constant
Java has three visibility modifiers: public, private, and
protected
We will discuss the protected modifier later in the course
39. Visibility Modifiers - Classes
A class can be defined either with the public modifier
or without a visibility modifier.
If a class is declared as public it can be used by any other
class
If a class is declared without a visibility modifier it has a
default visibility. This draws a limit to which other classes
can use this class (classes in the same package). We will
discuss default visibility later in the course.
Classes that define a new type of objects, that are
supposed to be used anywhere, should be declared
public.
40. Visibility Modifiers - Members
A member is a field, a method or a constructor of the class.
Members of a class can be declared as private,
protected, public or without a visibility modifier:
Members that are declared without a visibility modifier are
said to have default visibility. We will discuss default and
protected visibility later in the course.
private int hours;
int hours;
public int hours;
41. Public Visibility
Members that are declared as public can be accessed from
any class that can access the class of the member
We expose methods that are part of the interface of the class
by declaring them as public
Example: the methods getHours(), secondElapsed()
and setTime() are part of the interface of class Clock so
we define them as public.
We do not want to reveal the internal representation of the
object’s data. So we usually do not declare its state variables
as public (encapsulation)
42. Private Visibility
A class member that is declared as private, can be
accessed only by code that is within the class of this
member.
We hide the internal implementation of the class by
declaring its state variables and auxiliary methods as
private.
Data hiding is essential for encapsulation.
43. Illegal Access - example
// Example of illegal access
class BankAccountTest {
public static void main(String[] args) {
BankAccount victim = new BankAccount(2398742);
victim.balance = victim.balance - 500;
// this will not compile!
}
}
public class BankAccount {
private long accountNumber;
private double balance;
// …
44. Encapsulation not Among Instances of Same
Class
Encapsulation is to protect the programmers and is thus
between the code of different classes
Sometimes object instances of the same class need to
access each other’s “guts” (e.g., for state copying - if we
want to create an identical instance of an object we have)
Example:
from within a BankAccount object, any private member of
a different BankAccount object can be accessed.
45. Encapsulation - example
public void transfer(double amount,
BankAccount targetAccount) {
withdraw(amount);
targetAccount.deposit(amount);
}
// alternative version (valid, but not so nice)
public void transfer(double amount,
BankAccount targetAccount) {
balance -= amount;
targetAccount.balance += amount;
}
46. Lesson 4 – Classes & Objects
UNIT D5 - API DOCUMENTATION
47. API Documentation
Your classes are often intended to be used by other
programmers
Programmers that use your class are not interested in the
way it is implemented. They want to use it as a whole and
are only interested in what it does and how to use it.
API (Application Programmer Interface) documentation is
a description of the interface of the class intended for the
application programmer who wants to use it.
To use the class, we need not (and should not) look at the
code. All that is needed is the class API.
48. API Documentation
The JDK contains a special tool for the generation of API
documentation for your classes, called javadoc.
Any documentation which is part of the interface begins
with /** (double asterick) and ends with */
javadoc takes as input Java programs and automatically
generates documentation using:
the public/protected method signatures
the documentation comments (enclosed by /** … */).
The output is an HTML file which can be viewed by an
internet browser.
49. Clock API Documentation
/**
* A clock represents a point of time in a 12
* hour period within a precision of seconds.
* Its range: 1:00:00 -- 12:59:59.
*/
public class Clock {
private int hours;
private int minutes;
private int seconds;
/**
* Constructs a Clock: Sets the clock to the
* specified time.
*/
public Clock(int hours, int minutes, int seconds){
//…
}
50. Clock API Documentation – cont.
/**
* Constructs a Clock: Sets the clock to 12:00:00
*/
public Clock(){
this(12,0,0);
}
/**
* Advances this clock by 1 second.
*/
public void secondElapsed() {
//…
}
//…
54. What should you comment?
You should put a documentation comment for the class
itself and for any member of the class which is part of its
interface.
All public constructors and methods should have
documentation comments.
Private methods are not part of the interface of the
class, thus javadoc skips them. (But you should still
comment them for internal purposes.)
In the rare cases that there are public fields, they should
have documentation comments.
55. API Documentation
Remember that documentation comments are written for
programmers who use your class as a whole. They should describe
only
What the class does,
How to use it.
Documentation comments should not describe how a class is
implemented.
Documentation comments should be
Short and descriptive,
Written in a simple language (ENGLISH),
Accurate.
Assume that the reader doesn’t know anything about your class
56. API Documentation Tags
Documentation comments can also include tagged
paragraphs that give a standard way to document several
features of the interface such as method parameters,
return values, etc.
A tagged paragraph begins with the symbol @ followed
with a tag keywords. Tags: @see, @author,
@version, @param, @return, @exception.
Documentation comments text can include HTML tags.
57. @param tag
/**
* Changes the current time to hour:minute:second
* @param hours The new hour value.
* @param minutes The new minutes value.
* @param seconds The new seconds value.
*/
public void setTime(int hours,
int minutes,
int seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
61. Naming
The names you use for your class and for its public
methods are part of the class API.
Good descriptive naming are crucial for a clear API.
General rules about naming:
Follow the Java conventions
Use descriptive names
Do not use abbreviations!
Make names long enough, not unnecessary long
Consist of words in English with no abbreviations
Use a dictionary
Read the style guidelines!
62. Changing the Implementation of
a Class
Encapsulation allows us to change an implementation of a
class without affecting other parts of the program.
Without encapsulation changes to implementation might
“break” the program - many changes
Why would we want to change the implementation?
Different implementations have different tradeoffs (e.g., space
conservation, efficiency etc.)
Example: a time instance in the day can be represented by
the number of seconds since midnight
Assume we want to change the implementation of the clock
- what is involved in the process?
63. Example of new Clock
implementation - page 1
/**
* A clock represents a point of time in a 12
* hour period within a precision of seconds.
* Its range: 01:00:00 -- 12:59:59.
*/
public class Clock {
private static final int SECONDS_IN_12H = 12*60*60;
private int secondsFromZero;
/**
* Constructs a Clock: Sets the clock to the
* specified time.
*/
public Clock(int hours, int minutes, int seconds){
secondsFromZero = ((hours%12) * 3600
+ minutes * 60 + seconds);
}
64. Example of new Clock
implementation - page 2
/**
* Constructs a Clock: Sets the clock to 12:00:00
*/
public Clock(){
secondsFromZero=0;
}
/**
* Advances this clock by 1 second.
*/
public void secondElapsed() {
secondsFromZero = (secondsFromZero+1) %
SECONDS_IN_12H;
}
//…
65. Example of new Clock
implementation - page 3
/**
* Returns the current hour
* @return The current hour (between 1 and 12).
*/
public void getHour() {
int h = secondsFromZero/3600;
return h > 0 ? h : 12 ;
}
// all the others can be written in the same way
67. Applet Methods
We saw in earlier applets the use the of the paint
method to draw the content of the of the applet on the
screen.
An applet has several other methods that perform
specific duties.
Because the applets are specifically designed to work
with web browsers, some particular applet methods are
designed around that concept.
public void paint(Graphics g)
68. Some Applet Methods
Initializes the applet. Called just after the applet is loaded.
Starts the applet. Called just after the applet is made active.
Stops the applet. Called just after the applet is made
inactive.
Destroys the applet. Called when when the browser is
exited.
public void init()
public void start()
public void stop()
public void destroy()
69. Init, start, stop, and destroy.
The init method is executed once when the applet is
first loaded, such as when the browser or the applet
viewer initially view the applet.
This is the place to to initialize the applet’s environment and
permanent data.
The start/stop methods of an applet are called when
the applet becomes active/inactive.
For example, after we use a browser to initially load an
applet start is called. When we leave the page, the applet
becomes inactive and stop is called. If we return to that
page the applet becomes active again and start is called.
init start stop destroy
70. Objects with Graphic
representation
Many programs are graphic
Many objects in such programs correspond to “graphic
objects” on the screen – this is good programming
practice.
Such a graphic object will know how to draw itself on the
screen
72. The Lineup programs
The LineUp applet, shown in the previous slide shows 4
stick figures of different heights and colors.
It uses a StickFigure class that represents a stick
figure of a certain height, color, and location.
The applet creates 4 StickFigure objects, of varying
color and random height.
The StickFigure objects are instantiated in the init
method of the applet, so they are created once when the
applet is loaded.
The paint method of LineUp simply requests that the
stick figures draw themselves.
73. StickFigure - 1
import java.awt.*;
public class StickFigure {
private int baseX;
private int baseY;
private Color color;
private int height;
public StickFigure(int center, int bottom,
Color shade, int size) {
baseX = center;
baseY = bottom;
color = shade;
height = size;
}
74. StickFigure - 2
public void draw(Graphics page) {
int top = baseY – height;
page.setColor(color);
//head
page.drawOval(baseX-10,top,20,20);
//trunk
page.drawLine(baseX,top+20,baseX,baseY-30);
page.drawLine(baseX,baseY-30,baseX-15,baseY);
//legs
page.drawLine(baseX,baseY-30,baseX+15,baseY);
//arms
page.drawLine(baseX,baseY-70,baseX-25,baseY-70);
page.drawLine(baseX,baseY-70,baseX+20,baseY-85);
}
75. LineUp - code
import java.applet.Applet;
import java.awt.*;
public class LineUp extends Applet
{
private final int APPLET_WIDTH = 400;
private final int APPLET_HEIGHT = 150;
private final int HEIGHT_MIN = 100;
private final int VARIANCE = 30;
private StickFigure figure1, figure2,
figure3, figure4;
76. LineUp - code
public void init ()
{
int h1, h2, h3, h4; // heights of figures
h1 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
h2 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
h3 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
h4 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
figure1 = new StickFigure(100,150,Color.red,h1);
figure2 = new StickFigure(150,150,Color.cyan,h2);
figure3 = new StickFigure(200,150,Color.green,h3);
figure4 = new StickFigure(250,150,Color.yellow,h4);
setBackground(Color.black);
setSize(APPLET_WIDTH, APPLET_HEIGHT);
}
78. Lesson 4 – Classes & Objects
UNIT D7 - STATIC AND AUXILIARY METHODS
79. The Static Modifier
The static modifier can be applied to variables or
methods
It associates a variable or method with the class rather
than an object
Methods that are declared as static do not act upon
any particular object. They just encapsulate a given task,
a given algorithm.
We can write a class that is a collection of static
methods. Such a class isn’t meant to define new type of
objects. It is just used as a library for utilities that are
related in some way.
80. Example - a Math Class
/**
* A library of mathematical methods.
*/
public class Math {
/**
* Computes the trigonometric sine of an angle.
*/
public static double sin(double x) { … }
/**
* Computes the logarithm of a given number.
*/
public static double log(double x) { … }
// ...
81. Static Variables
A variable that is declared static is associated with the
class itself and not with an instance of it.
Static variables are also called class variables.
We use static variables to store information that is not
associated with a given object, but is relevant to the class.
We have already seen such usage - constants of a class
(final static)
82. Static Variables - Example
public class BankAccount {
private long accountNumber;
private double balance;
private static int numberOfAccounts = 0;
public BankAccount() {
this.accountNumber = ++numberOfAccounts;
this.balance = 0;
}
public static int getNumberOfAccounts {
return numberOfAccounts;
}
}
83. Static Methods and Instance
Variables
Static methods:
cannot reference instance variables (e.g. - access instance
variable when an object doesn’t exist)
can reference static variables or local variables (within the
method)
this has no meaning inside a static method, thus its use
inside a static method is not allowed.
Instance methods can access static variables.
84. Division Into Methods
Complicated tasks or tasks that occur often within a class
should be wrapped in a method
If you can clearly define the task, you should probably
make it a method.
This results in a readable and manageable code
This is very helpful when implementing algorithms, or
when we need “helper” methods in classes.
85. Division into methods – interest
calculation
public class BankAccount {
final static int DAYS_IN_YEAR = 365;
public void earnDailyInterest(int days){
double rate = 1 + interestRate()/DAYS_IN_YEAR;
for(int j=0 ; j<days ; j++)
balance *= rate;
}
private double interestRate() {
return (balance>100000) ? 0.06 : 0.05;
}
86. Division into Methods – Printing
primes
public class PrintPrimes {
public static void main(String[] args) {
for(j = 2 ; j < 1000 ; j++){
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int n){
for(int j=2 ; j < n ; j++)
if (n%j == 0)
return false;
return true;
}
}