Stuck with your Ruby Programming Assignment. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
In this chapter we will review how to work with text files in C#. We will explain what a stream is, what its purpose is, and how to use it. We will explain what a text file is and how can you read and write data to a text file and how to deal with different character encodings. We will demonstrate and explain the good practices for exception handling when working with files. All of this will be demonstrated with many examples in this chapter
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
In this chapter we are going to get familiar with some of the basic presentations of data in programming: lists and linear data structures. Very often in order to solve a given problem we need to work with a sequence of elements. For example, to read completely this book we have to read sequentially each page, i.e. to traverse sequentially each of the elements of the set of the pages in the book. Depending on the task, we have to apply different operations on this set of data. In this chapter we will introduce the concept of abstract data types (ADT) and will explain how a certain ADT can have multiple different implementations. After that we shall explore how and when to use lists and their implementations (linked list, doubly-linked list and array-list). We are going to see how for a given task one structure may be more convenient than another. We are going to consider the structures "stack" and "queue", as well as their applications. We are going to get familiar with some implementations of these structures.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
In this chapter we will review how to work with text files in C#. We will explain what a stream is, what its purpose is, and how to use it. We will explain what a text file is and how can you read and write data to a text file and how to deal with different character encodings. We will demonstrate and explain the good practices for exception handling when working with files. All of this will be demonstrated with many examples in this chapter
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
In this chapter we are going to get familiar with some of the basic presentations of data in programming: lists and linear data structures. Very often in order to solve a given problem we need to work with a sequence of elements. For example, to read completely this book we have to read sequentially each page, i.e. to traverse sequentially each of the elements of the set of the pages in the book. Depending on the task, we have to apply different operations on this set of data. In this chapter we will introduce the concept of abstract data types (ADT) and will explain how a certain ADT can have multiple different implementations. After that we shall explore how and when to use lists and their implementations (linked list, doubly-linked list and array-list). We are going to see how for a given task one structure may be more convenient than another. We are going to consider the structures "stack" and "queue", as well as their applications. We are going to get familiar with some implementations of these structures.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
In C, a struct models what a thing has/is (i.e., the data, also called the characteristics), but not what it does (its behavior, represented by functions).
The functions are outside and separate from structs.
In C++, the characteristics and behavior are integrated into a single structure, called object.
The data type of an object is the class of the object
The packaging of the data and the functions into a class type is called data encapsulation.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
Scala 3 Is Coming: Martin Odersky Shares What To KnowLightbend
Join Dr. Martin Odersky, the creator of Scala and co-founder of Lightbend, on a tour of what is in store and highlight some of his favorite features of Scala 3!
An invited talk by Xavier Leroy explaining the current state of OCaml at the OCaml Users and Developers Workshop 2014. http://ocaml.org/meetings/ocaml/2014/
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
In C, a struct models what a thing has/is (i.e., the data, also called the characteristics), but not what it does (its behavior, represented by functions).
The functions are outside and separate from structs.
In C++, the characteristics and behavior are integrated into a single structure, called object.
The data type of an object is the class of the object
The packaging of the data and the functions into a class type is called data encapsulation.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
Scala 3 Is Coming: Martin Odersky Shares What To KnowLightbend
Join Dr. Martin Odersky, the creator of Scala and co-founder of Lightbend, on a tour of what is in store and highlight some of his favorite features of Scala 3!
An invited talk by Xavier Leroy explaining the current state of OCaml at the OCaml Users and Developers Workshop 2014. http://ocaml.org/meetings/ocaml/2014/
Stuck with your Network Programming Assignment Help. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
Interprocess communication Assignment help. Stuck with your System Programming Assignment. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
In general, a factorial experiment involves several variables.
One variable is the response variable, which is sometimes called the outcome variable or the dependent variable.
The other variables are called factors.
When there are different variables with the same name, there are different possible bindings for that name
Not just variables: type names, constant names, function names, etc.
A definition is anything that establishes a possible binding for a name
Stuck with Payout Policy and cash dividend assignment help?. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
Signals are software interrupts that give us a way to handle asynchronous events.Stuck with your System Programming Assignment. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
CRM or Customer Relationship Management refers to the methodologies and tools that help businesses manage customer relationships in an organized way. The main objective is to learn more about the needs and behavior of customers. It helps to build stronger relationships with them.
An introduction into Googles programming language Go, which had its first release in March 2012. The talk has been held at the regulars' table of the GTUG Bremen.
Apple's Swift has achieved the top place in Stack Overflow's "Most Loved" list of programming languages in its 2015 Developer Survey. Based on information gleaned from GitHub and Stack Overflow, analyst firm RedMonk has seen Swift's popularity ranking soar from 68 to 22 in an unprecedented 6 months.
The "Extreme Swift" event does not require advanced, or even any, knowledge of Swift. Learn about some of the more outrageous features of the language which help explain what the fuss is all about!
Never look at programming the same way again — even if you never end up writing a single line of Swift code in your life.
Description of the project Purpose To implement a simple au.pdfadcrates2010
Description of the project
Purpose: To implement a simple automatic word-completion system.
Task 1: Implement algorithms for DLB insertion and traversal.
Task 2: Implement an algorithm for retrieving one word prediction.
Background
Autocomplete is a commonly used feature in mobile phones, text editors, and search engines. As
a user types in letters, the system shows a list of word predictions to help the user complete the
word they are typing. The core of an efficient autocompletion system is a fast algorithm for
retrieving word predictions based on the user input. The word predictions are all the words (in a
given dictionary) that start with what the user has typed so far (i.e., the list of words for which the
user's input is a prefix).
In this assignment we will build a simple autocompletion system using a DLB trie which allows the
user to add a new word to its dictionary when none of the predictions are selected by the user.
The AutoCompleteInterface defines a Java interface for a dictionary that provides word predictions
for such an autocompletion system. Besides storing a set of words, the dictionary keeps track of a
prefix String, which starts with the empty String. You will implement methods to add one character
to and delete the last character of that prefix String. You will also implement methods that use that
prefix String for various operations, such as checking if the prefix String is one of the words in the
dictionary, retrieving the number of words that have the prefix String as a prefix, and adding the
prefix String to the dictionary.
Details
In the first part of this assignment, you will implement algorithms for:
inserting a StringBuilder object into a DLB trie by filling in the add(String word) method below. You
may want to add and call a private recursive helper method.
The DLBNode class is already defined for you in AutoComplete.java. You will use a doubly-linked
list of siblings, a child reference, and an upwards reference to the node's parent. The isWord field
of a node is true if and only if the node is at the end of a word in the dictionary. The size field
keeps track of the number of nodes with isWord==true in the subtree rooted at the node, including
the node itself. The add method should update the size field for some of the nodes that it goes
over. You will need to think about for which nodes size should be incremented.
The next set of the methods modify the prefix String maintained by the dictionary. These methods
are: advance(char c) for appending a character to the prefix String, retreat() for deleting the last
character, and reset() for resetting it back to the empty String. More details about these methods
can be found below. Your code should maintain a DLBNode currentNode reference to always
point to the DLB node at the end of the prefix String. currentNode is null when the prefix String is
"", moves over the sibling list of the root node upon the first call to advance, moves possibly
sideways then down the tr.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
A Recovering Java Developer Learns to GoMatt Stine
As presented at OSCON 2014.
The Go programming language has emerged as a favorite tool of DevOps and cloud practitioners alike. In many ways, Go is more famous for what it doesn’t include than what it does, and co-author Rob Pike has said that Go represents a “less is more” approach to language design.
The Cloud Foundry engineering teams have steadily increased their use of Go for building components, starting with the Router, and progressing through Loggregator, the CLI, and more recently the Health Manager. As a “recovering-Java-developer-turned-DevOps-junkie” focused on helping our customers and community succeed with Cloud Foundry, it became very clear to me that I needed to add Go to my knowledge portfolio.
This talk will introduce Go and its distinctives to Java developers looking to add Go to their toolkits. We’ll cover Go vs. Java in terms of:
* type systems
* modularity
* programming idioms
* object-oriented constructs
* concurrency
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
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 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.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
1. 3/25/2014
1
More Ruby programming
Iterators, duck typing, inheritance,
and mixins
Iterators
• 3.times { puts "hi" } # output “hi” 3 times
• [4,6,8].each { puts "hi" } # can "ignore" argument
• y = 7
[4,6,8].each { |x|
y = y + x
puts y
}
What is the value of y?
Iterators
• arr = [4,6,8,10]
arr2 = arr.map { |x| x + 1 }
puts arr2 # output another array,
# each element is the result of the block
• sum = arr.inject { |acc,elt| acc + elt }
puts sum # inject is like fold function
# acc is the initial value, elt is the array element
# result of the block is used as initial value
# to apply the block to the next array element
Iterators
• puts (arr.any? { |elt| elt < 0 })
# prints true if one element is negative
• def foo
eight = yield 4
twelve = yield 6
eight + twelve
end
• puts (foo { |x| x + x } ) # what is the output?
Closure
• cl = lambda {|z| z * y}
q = cl.call(9)
puts q
• def foo2 f
eight = f.call 4
twelve = bar f
eight + twelve
end
def bar f
f.call 6
end
puts (foo2 (lambda { |x| x + x })
Duck typing
• Use an instance that “behaves enough like”
the expected ones.
def double x
x + x
end
– double applies to any class of objects that has a +
method that takes self as argument
2. 3/25/2014
2
Inheritance
• If a class C extends class D, then every
instance of C is also an instance of D
– C inherits the methods of D
– C can add new methods
– C can override inherited methods
– Unlike Java, Ruby fields are not part of a class
definition and therefore, not inherited
Point class
class Point
attr_reader :x, :y
attr_writer :x, :y
def initialize(x,y)
@x = x
@y = y
end
def distFromOrigin
Math.sqrt(x * x + y * y) # uses getter methods
end
end
ColorPoint extends Point
class ColorPoint < Point
attr_reader :color
attr_writer :color
# (say p.color = "green" rather than needing
# p.myColorSetter("green") which does @color="green" in its body)
def initialize(x,y,c="clear") # or could skip this and color starts unset
super(x,y)
@color = c
end
end
3D point extends point
class ThreeDPoint < Point
attr_reader :z
attr_writer :z
def initialize(x,y,z)
super(x,y)
@z = z
end
def distFromOrigin
d = super
Math.sqrt(d * d + z * z)
end
end
Polar point extends point
class PolarPoint < Point
def initialize (r, theta)
@r = r
@theta = theta
end
def x
@r * Math.cos(@theta)
end
def y
@r * Math.sin(@theta)
end
…
# distFromOrigin already works!!!
end
Polar point extends point
class PolarPoint < Point
…
def x= a
b = y # avoids multiple calls to y method
@theta = Math.atan (b / a)
@r = Math.sqrt(a*a + b*b)
self
end
def y= b
a = x # avoid multiple calls to x method
@theta = Math.atan (b / a)
@r = Math.sqrt (a*a + b*b)
self
end
# distFromOrigin already works!!!
end
3. 3/25/2014
3
Dynamic dispatch
def distFromOrigin
Math.sqrt(x * x + y * y) # uses getter methods
end
Math.sqrt(self.x() * self.x() + self.y() * self.y())
This method inherited from Point class still works
because the method “x” and “y” are overridden
in the subclass PolarPoint
Multiple inheritance, interfaces, and
mixins
• Languages (C++) with multiple inheritance let one class
extend multiple other classes
– Most powerful option
– Has semantic problems
– Java and Ruby do not use it
• Interfaces: Java has single inheritance but a Java class can
implement multiple interfaces
– An interface defines method signatures but not implementation
• Mixins: Ruby allows a class to have only one super class but
can include any number of mixins
– Mixin is “just a pile of methods”
– Mixin provides behavior while interface only provides types,
which is not an issue for dynamic languages such as Ruby
Multiple Inheritance
• In some languages (such as C++) a class can
have more than one base class
• Seems simple at first: just inherit fields and
methods from all the base classes
• For example: a multifunction printer
MultiFunction
Printer Copier Scanner Fax
Collision Problem
• The different base classes are unrelated,
and may not have been designed to be
combined
• Scanner and Fax might both have a
method named transmit
• When MultiFunction.transmit is
called, what should happen?
MultiFunction
Printer Copier Scanner Fax
Diamond Problem
• A class may inherit from the same base
class through more than one path
• If A defines a field x, then B has one and so
does C
• Does D get two of them?
D
B C
A
Solvable, But…
• A language that supports multiple inheritance
must have mechanisms for handling these
problems
• Not all that tricky
• The question is, is the additional power worth
the additional language complexity?
• Java’s designers did not think so
4. 3/25/2014
4
Living Without Multiple Inheritance
• One benefit of multiple inheritance is that a
class can have several unrelated types (like
Copier and Fax)
• This can be done in Java by using interfaces:
a class can implement any number of
interfaces
• Another benefit is inheriting
implementation from multiple base classes
• This is harder to accomplish with Java
public class MultiFunction {
private Printer myPrinter;
private Copier myCopier;
private Scanner myScanner;
private Fax myFax;
public void copy() {
myCopier.copy();
}
public void transmitScanned() {
myScanner.transmit();
}
public void sendFax() {
myFax.transmit();
}
…
}
Forwarding
Interfaces
• A method prototype just gives the method
name and type—no method body
• An interface in Java is a collection of
method prototypes
public interface Drawable {
void show(int xPos, int yPos);
void hide();
}
Implementing Interfaces
• A class can declare that it implements a
particular interface
• Then it must provide public method
definitions that match those in the interface
Examples
public class Icon implements Drawable {
public void show(int x, int y) {
… method body …
}
public void hide() {
… method body …
}
…more methods and fields…
}
public class Square implements Drawable, Scalable {
… all required methods of all interfaces implemented …
}
Why Use Interfaces?
• An interface can be implemented by many
classes:
• Interface name can be used as a reference
type:
public class Window implements Drawable …
public class MousePointer implements Drawable …
public class Oval implements Drawable …
Drawable d;
d = new Icon("i1.gif");
d.show(0,0);
d = new Oval(20,30);
d.show(0,0);
5. 3/25/2014
5
Polymorphism With Interfaces
• Class of object referred to by d is not
known at compile time
• It is some class that implements
Drawable, so it has show and hide
methods that can be called
static void flashoff(Drawable d, int k) {
for (int i = 0; i < k; i++) {
d.show(0,0);
d.hide();
}
}
A More Complete Example
• A Worklist interface for a collection of
String objects
• Can be added to, removed from, and tested
for emptiness
public interface Worklist {
/**
* Add one String to the worklist.
* @param item the String to add
*/
void add(String item);
/**
* Test whether there are more elements in the
* worklist: that is, test whether more elements
* have been added than have been removed.
* @return true iff there are more elements
*/
boolean hasMore();
/**
* Remove one String from the worklist and return
* it. There must be at least one element in the
* worklist.
* @return the String item removed
*/
String remove();
}
Interface Documentation
• Comments are especially important in an
interface, since there is no code to help the
reader understand what each method is
supposed to do
• Worklist interface does not specify
ordering: could be a stack, a queue, or
something else
• We will do an implementation as a stack,
implemented using linked lists
/**
* A Node is an object that holds a String and a link
* to the next Node. It can be used to build linked
* lists of Strings.
*/
public class Node {
private String data; // Each node has a String...
private Node link; // and a link to the next Node
/**
* Node constructor.
* @param theData the String to store in this Node
* @param theLink a link to the next Node
*/
public Node(String theData, Node theLink) {
data = theData;
link = theLink;
}
6. 3/25/2014
6
/**
* Accessor for the String data stored in this Node.
* @return our String item
*/
public String getData() {
return data;
}
/**
* Accessor for the link to the next Node.
* @return the next Node
*/
public Node getLink() {
return link;
}
}
/**
* A Stack is an object that holds a collection of
* Strings.
*/
public class Stack implements Worklist {
private Node top = null; // top Node in the stack
/**
* Push a String on top of this stack.
* @param data the String to add
*/
public void add(String data) {
top = new Node(data,top);
}
/**
* Test whether this stack has more elements.
* @return true if this stack is not empty
*/
public boolean hasMore() {
return (top!=null);
}
/**
* Pop the top String from this stack and return it.
* This should be called only if the stack is
* not empty.
* @return the popped String
*/
public String remove() {
Node n = top;
top = n.getLink();
return n.getData();
}
}
A Test
• Output: The cut worm forgives the plow.
• Other implementations of Worklist are
possible: Queue, PriorityQueue, etc.
Worklist w;
w = new Stack();
w.add("the plow.");
w.add("forgives ");
w.add("The cut worm ");
System.out.print(w.remove());
System.out.print(w.remove());
System.out.println(w.remove());
Mixins
• Ruby mixins are somewhere between multiple
inheritance and interfaces
– They provide actual code for classes to include them but
they are not classes themselves
– Do not have constructors or a separate notion of fields
module Color
attr_accessor :color
def darken
self.color = "dark " + self.color
end
end
Include a mixin in class definition
module Color
attr_accessor :color
def darken
self.color = "dark " + self.color
end
end
class ColorPoint < Point
include Color
end
7. 3/25/2014
7
Method look up
• obj.m # obj is an instance of the class C
– Look in C for method m first
– Then look in the mixins included in C
• Later ones shadow earlier ones
– Look in C’s superclass
– Look in C’s superclass’ mixins
– Look in C’s super-superclass
– Continue until m is found or reach the Object class
Mixin may call hook methods
module Doubler
def double
self + self # uses self’s + method, not defined in Doubler
end
end
class AnotherPoint
attr_accessor :x, :y
include Doubler
def + other # add two points
ans = AnotherPoint.new
ans.x = self.x + other.x
ans.y = self.y + other.y
ans
end
end
class String
include Doubler
end
Convenient Ruby mixins
• Both Enumerable and Comparable are mixins in
Ruby
• Comparable provides =, !=, >, >=, <, and <=
– Assume the classes that include comparable has the
method <=>
• a <=> b < 0 if a < b
• a <=> b > 0 if a > b
• a <=> b = 0 if a == b
– A class like Integer only needs to define <=> method
and then include Comparable to have a bunch of
methods for comparison
An example use of Comparable
class Name
attr_accessor :first, :middle, :last
include Comparable
def initialize(first,last,middle="")
@first = first
@last = last
@middle = middle
end
def <=> other
l = @last <=> other.last # <=> defined on strings
return l if l != 0
f = @first <=> other.first
return f if f != 0
@middle <=> other.middle
end
end
Define Comparable methods
def > other
(self <=> other) > 0
end
Enumerable module
• Enumerable defines methods such as any?,
map, and inject
– Assume the enumerable classes have “each”
method
– Array class defines “each” method and includes
Enumerable mixin
8. 3/25/2014
8
Enumerable example
class MyRange
include Enumerable
def initialize(low,high)
@low = low
@high = high
end
def each
i=@low
while i <= @high
yield i
i=i+1
end
end
end
Enumerable example
class MyRange
include Enumerable
def initialize(low,high)
@low = low
@high = high
end
def each
i=@low
while i <= @high
yield i
i=i+1
end
end
end
MyRange.new(4,8).inject{|x,y| x+y}
Enumerable example
class MyRange
include Enumerable
def initialize(low,high)
@low = low
@high = high
end
def each
i=@low
while i <= @high
yield i
i=i+1
end
end
end
MyRange.new(4,8).inject{|x,y| x+y}
def map
arr = []
each {|x| arr.push x }
arr
end