SlideShare a Scribd company logo
1 of 51
Download to read offline
6.092: Introduction to Java
6: Design, Debugging,
Interfaces
Assignment 5: main()
Programs start at a main() method, but
many classes can have main()
public class SimpleDraw {
/* ... stuff ... */
public static void main(String args[]) {
SimpleDraw content = new SimpleDraw(new DrawGraphics());
/* ... more stuff ... */
}
}
Assignment 5: main()
Programs start at a main() method, but
many classes can have main()
public class SimpleDraw {
/* ... stuff ... */
public static void main(String args[]) {
SimpleDraw content = new SimpleDraw(new DrawGraphics());
/* ... more stuff ... */
}
}
public class DrawGraphics {
BouncingBox box;
public DrawGraphics() {
box = new BouncingBox(200, 50, Color.RED);
}
public void draw(Graphics surface) {
surface.drawLine(50, 50, 250, 250);
box.draw(surface);
}
}
public class DrawGraphics {
BouncingBox box; // a field or member variable
public DrawGraphics() {
box = new BouncingBox(200, 50, Color.RED);
}
public void draw(Graphics surface) {
surface.drawLine(50, 50, 250, 250);
box.draw(surface);
}
}
public class DrawGraphics {
BouncingBox box;
public DrawGraphics() { // constructor
box = new BouncingBox(200, 50, Color.RED);
}
public void draw(Graphics surface) {
surface.drawLine(50, 50, 250, 250);
box.draw(surface);
}
}
public class DrawGraphics {
public void draw(Graphics surface) {
surface.drawLine(50, 50, 250, 250);
box.draw(surface);
surface.fillRect (150, 100, 25, 40);
surface.fillOval (40, 40, 25, 10);
surface.setColor (Color.YELLOW);
surface.drawString ("Mr. And Mrs. Smith", 200, 10);
}
}
public class DrawGraphics {
ArrayList<BouncingBox> boxes = new ArrayList<BouncingBox>();
public DrawGraphics() {
boxes.add(new BouncingBox(200, 50, Color.RED));
boxes.add(new BouncingBox(10, 10, Color.BLUE));
boxes.add(new BouncingBox(100, 100, Color.GREEN));
boxes.get(0).setMovementVector(1, 0);
boxes.get(1).setMovementVector(-3, -2);
boxes.get(2).setMovementVector(1, 1);
}
public void draw(Graphics surface) {
for (BouncingBox box : boxes) {
box.draw(surface);
}
}
}
Outline
Good program design
Debugging
Interfaces
What is a good program?
Correct / no errors
Easy to understand
Easy to modify / extend
Good performance (speed)
Consistency
Writing code in a consistent way makes it
easier to write and understand
Programming “style” guides: define rules
about how to do things
Java has some widely accepted
“standard” style guidelines
Naming
Variables: Nouns, lowercase first letter, capitals
separating words
x, shape, highScore, fileName
Methods: Verbs, lowercase first letter
getSize(), draw(), drawWithColor()
Classes: Nouns, uppercase first letter
Shape, WebPage, EmailAddress
Good Class Design
Good classes: easy to understand and use
• Make fields and methods private by default
• Only make methods public if you need to
• If you need access to a field, create a
method:
public int getBar() { return bar; }
Debugging
The process of finding and correcting an
error in a program
A fundamental skill in programming
Step 1: Donʼt Make Mistakes
Donʼt introduce errors in the first place
Step 1: Donʼt Make Mistakes
Donʼt introduce errors in the first place
• Reuse: find existing code that does
what you want
• Design: think before you code
• Best Practices: Recommended
procedures/techniques to avoid
common problems
Design: Pseudocode
A high-level, understandable description
of what a program is supposed to do
Donʼt worry about the details, worry about
the structure
Pseudocode: Interval Testing
Example:
Is a number within the interval [x, y)?
If number < x return false
If number > y return false
Return true
Design
Visual design for objects, or how a
program works
Donʼt worry about specific notation, just
do something that makes sense for you
Scrap paper is useful
SimpleDraw
DrawGraphics
ArrayList
BouncingBox BouncingBox BouncingBox
Step 2: Find Mistakes Early
Easier to fix errors the earlier you find
them
• Test your design
• Tools: detect potential errors
• Test your implementation
• Check your work: assertions
Testing: Important Inputs
Want to check all “paths” through the
program.
Think about one example for each “path”
Example:
Is a number within the interval [x, y)?
Intervals: Important Cases
Below the lower bound
Equal to the lower bound
Within the interval
Equal to the upper bound
Above the upper bound
Intervals: Important Cases
What if lower bound > upper bound?
What if lower bound == upper bound?
(hard to get right!)
Pseudocode: Interval Testing
Is a number within the interval [x, y)?
If number < x return false
If number > y return false
Return true
Pseudocode: Interval Testing
Is a number within the interval [x, y)?
Is 5 in the interval [3, 5)?
If number < x return false
If number > y return false
Return true
Pseudocode: Interval Testing
Is a number within the interval [x, y)?
Is 5 in the interval [3, 5)?
If number < x return false
If number >= y return false
Return true
Tools: Eclipse Warnings
Warnings: may not be a mistake, but it
likely is.
Suggestion: always fix all warnings
Extra checks: FindBugs and related tools
Unit testing: JUnit makes testing easier
Assertions
Verify that code does what you expect
If true: nothing happens
If false: program crashes with error
Disabled by default (enable with ‐ea)
assert difference >= 0;
void printDifferenceFromFastest(int[] marathonTimes) {
int fastestTime = findMinimum(marathonTimes);
for (int time : marathonTimes) {
int difference = time - fastestTime;
assert difference >= 0;
System.out.println("Difference: " + difference);
}
}
Step 3: Reproduce the Error
• Figure out how to repeat the error
• Create a minimal test case
Go back to a working version, and
introduce changes one at a time until
the error comes back
Eliminate extra stuff that isnʼt used
Step 4: Generate Hypothesis
What is going wrong?
What might be causing the error?
Question your assumptions: “x canʼt be
possible:” What if it is, due to something
else?
Step 5: Collect Information
If x is the problem, how can you verify?
Need information about what is going
on inside the program
System.out.println() is very powerful
Eclipse debugger can help
Step 6: Examine Data
Examine your data
Is your hypothesis correct?
Fix the error, or generate a new
hypothesis
Why Use Methods?
Write and test code once, use it multiple
times: avoid duplication
Eg. Library.addBook()
Why Use Methods?
Use it without understanding how it works:
encapsulation / information hiding
Eg. How does System.out.println() work?
Why Use Objects?
Objects combine a related set of variables
and methods
Provide a simple interface
(encapsulation again)
Implementation / Interface
Library
Book[] books;
int numBooks;
String address;
void addBook(Book b) {
books[numBooks] = b;
numBooks++;
}
Library
void addBook(Book b);
Java Interfaces
Manipulate objects, without knowing how
they work
Useful when you have similar but not
identical objects
Useful when you want to use code written
by others
Interface Example: Drawing
public class BouncingBox {
public void draw(Graphics surface) {
// … code to draw the box …
}
}
// … draw boxes …
for (BouncingBox box : boxes) {
box.draw(surface);
}
Interface Example: Drawing
public class Flower {
public void draw(Graphics surface) {
// … code to draw a flower …
}
}
// … draw flowers …
for (Flower flower : flowers) {
flower.draw(surface);
}
public class DrawGraphics {
ArrayList<BouncingBox> boxes = new ArrayList<BouncingBox>();
ArrayList<Flower> flowers = new ArrayList<Flower>();
ArrayList<Car> cars = new ArrayList<Car>();
public void draw(Graphics surface) {
for (BouncingBox box : boxes) {
box.draw(surface);
}
for (Flower flower : flowers) {
flower.draw(surface);
}
for (Car car : cars) {
car.draw(surface);
}
}
}
public class DrawGraphics {
ArrayList<Drawable> shapes = new ArrayList<Drawable>();
ArrayList<Flower> flowers = new ArrayList<Flower>();
ArrayList<Car> cars = new ArrayList<Car>();
public void draw(Graphics surface) {
for (Drawable shape : shapes) {
shape.draw(surface);
}
for (Flower flower : flowers) {
flower.draw(surface);
}
for (Car car : cars) {
car.draw(surface);
}
}
}
Interfaces
Set of classes that share methods
Declare an interface with the common
methods
Can use the interface, without knowing an
objectʼs specific type
Interfaces: Drawable
import java.awt.Graphics;
interface Drawable {
void draw(Graphics surface);
void setColor(Color color);
}
Implementing Interfaces
Implementations provide complete
methods:
import java.awt.Graphics;
class Flower implements Drawable {
// ... other stuff ...
public void draw(Graphics surface) {
// ... code to draw a flower here ...
}
}
Interface Notes
Only have methods (mostly true)
Do not provide code, only the definition
(called signatures)
A class can implement any number of
interface
Using Interfaces
Can only access stuff in the interface.
Drawable d = new BouncingBox(…);
d.setMovementVector(1, 1);
The method setMovementVector(int, int)
is undefined for the type Drawable
Casting
If you know that a variable holds a
specific type, you can use a cast:
Drawable d = new BouncingBox(…);
BouncingBox box = (BouncingBox) d;
box.setMovementVector(1, 1);
Assignment: More graphics
Start a new project: code has changed.
MIT OpenCourseWare
http://ocw.mit.edu
6.092 Introduction to Programming in Java
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More Related Content

Similar to Introduction to Java Programming Concepts Including Main Methods, Debugging and Interfaces

A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScriptDenis Voituron
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 
Software Design
Software DesignSoftware Design
Software DesignSpy Seat
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating resultsbodaceacat
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating resultsSara-Jayne Terp
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classesAnup Burange
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Lesson plan 2 matt 3
Lesson plan 2 matt 3Lesson plan 2 matt 3
Lesson plan 2 matt 3Max Friel
 
Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Ha Nguyen
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Chapter 2.4
Chapter 2.4Chapter 2.4
Chapter 2.4sotlsoc
 
Module Six Assignment Guidelines and Rubric.htmlOverviewMa.docx
Module Six Assignment Guidelines and Rubric.htmlOverviewMa.docxModule Six Assignment Guidelines and Rubric.htmlOverviewMa.docx
Module Six Assignment Guidelines and Rubric.htmlOverviewMa.docxroushhsiu
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Dimitris Dranidis
 

Similar to Introduction to Java Programming Concepts Including Main Methods, Debugging and Interfaces (20)

A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Software Design
Software DesignSoftware Design
Software Design
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating results
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating results
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Lesson plan 2 matt 3
Lesson plan 2 matt 3Lesson plan 2 matt 3
Lesson plan 2 matt 3
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Debug - MITX60012016-V005100
Debug - MITX60012016-V005100
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Chapter 2.4
Chapter 2.4Chapter 2.4
Chapter 2.4
 
Module Six Assignment Guidelines and Rubric.htmlOverviewMa.docx
Module Six Assignment Guidelines and Rubric.htmlOverviewMa.docxModule Six Assignment Guidelines and Rubric.htmlOverviewMa.docx
Module Six Assignment Guidelines and Rubric.htmlOverviewMa.docx
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
 

Recently uploaded

Hi FI Call Girl Ahmedabad 7397865700 Independent Call Girls
Hi FI Call Girl Ahmedabad 7397865700 Independent Call GirlsHi FI Call Girl Ahmedabad 7397865700 Independent Call Girls
Hi FI Call Girl Ahmedabad 7397865700 Independent Call Girlsssuser7cb4ff
 
Unit 1 - introduction to environmental studies.pdf
Unit 1 - introduction to environmental studies.pdfUnit 1 - introduction to environmental studies.pdf
Unit 1 - introduction to environmental studies.pdfRajjnish1
 
原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证
原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证
原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证jdkhjh
 
Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...Open Access Research Paper
 
Philippines-Native-Chicken.pptx file copy
Philippines-Native-Chicken.pptx file copyPhilippines-Native-Chicken.pptx file copy
Philippines-Native-Chicken.pptx file copyKristineRoseCorrales
 
NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...
NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...
NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...Amil baba
 
ENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental lawENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental lawnitinraj1000000
 
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130Suhani Kapoor
 
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...Aqsa Yasmin
 
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一F dds
 
5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdf
5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdf5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdf
5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdfsrivastavaakshat51
 
885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Education885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Educationz xss
 
Delivering nature-based solution outcomes by addressing policy, institutiona...
Delivering nature-based solution outcomes by addressing  policy, institutiona...Delivering nature-based solution outcomes by addressing  policy, institutiona...
Delivering nature-based solution outcomes by addressing policy, institutiona...CIFOR-ICRAF
 
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170simranguptaxx69
 
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhidelih Escorts
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...Delhi Escorts
 

Recently uploaded (20)

Hi FI Call Girl Ahmedabad 7397865700 Independent Call Girls
Hi FI Call Girl Ahmedabad 7397865700 Independent Call GirlsHi FI Call Girl Ahmedabad 7397865700 Independent Call Girls
Hi FI Call Girl Ahmedabad 7397865700 Independent Call Girls
 
Unit 1 - introduction to environmental studies.pdf
Unit 1 - introduction to environmental studies.pdfUnit 1 - introduction to environmental studies.pdf
Unit 1 - introduction to environmental studies.pdf
 
原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证
原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证
原版1:1复刻塔夫斯大学毕业证Tufts毕业证留信学历认证
 
Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...
 
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
 
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls ServicesGandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
 
Philippines-Native-Chicken.pptx file copy
Philippines-Native-Chicken.pptx file copyPhilippines-Native-Chicken.pptx file copy
Philippines-Native-Chicken.pptx file copy
 
NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...
NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...
NO1 Famous Amil In Karachi Best Amil In Karachi Bangali Baba In Karachi Aamil...
 
FULL ENJOY Call Girls In kashmiri gate (Delhi) Call Us 9953056974
FULL ENJOY Call Girls In  kashmiri gate (Delhi) Call Us 9953056974FULL ENJOY Call Girls In  kashmiri gate (Delhi) Call Us 9953056974
FULL ENJOY Call Girls In kashmiri gate (Delhi) Call Us 9953056974
 
ENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental lawENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental law
 
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
 
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
EARTH DAY Slide show EARTHDAY.ORG is unwavering in our commitment to end plas...
 
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
办理学位证(KU证书)堪萨斯大学毕业证成绩单原版一比一
 
5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdf
5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdf5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdf
5 Wondrous Places You Should Visit at Least Once in Your Lifetime (1).pdf
 
885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Education885MTAMount DMU University Bachelor's Diploma in Education
885MTAMount DMU University Bachelor's Diploma in Education
 
Delivering nature-based solution outcomes by addressing policy, institutiona...
Delivering nature-based solution outcomes by addressing  policy, institutiona...Delivering nature-based solution outcomes by addressing  policy, institutiona...
Delivering nature-based solution outcomes by addressing policy, institutiona...
 
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
Call Girls Sarovar Portico Naraina Hotel, New Delhi 9873777170
 
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
 
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
9873940964 Full Enjoy 24/7 Call Girls Near Shangri La’s Eros Hotel, New Delhi
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
 

Introduction to Java Programming Concepts Including Main Methods, Debugging and Interfaces

  • 1. 6.092: Introduction to Java 6: Design, Debugging, Interfaces
  • 2. Assignment 5: main() Programs start at a main() method, but many classes can have main() public class SimpleDraw { /* ... stuff ... */ public static void main(String args[]) { SimpleDraw content = new SimpleDraw(new DrawGraphics()); /* ... more stuff ... */ } }
  • 3. Assignment 5: main() Programs start at a main() method, but many classes can have main() public class SimpleDraw { /* ... stuff ... */ public static void main(String args[]) { SimpleDraw content = new SimpleDraw(new DrawGraphics()); /* ... more stuff ... */ } }
  • 4. public class DrawGraphics { BouncingBox box; public DrawGraphics() { box = new BouncingBox(200, 50, Color.RED); } public void draw(Graphics surface) { surface.drawLine(50, 50, 250, 250); box.draw(surface); } }
  • 5. public class DrawGraphics { BouncingBox box; // a field or member variable public DrawGraphics() { box = new BouncingBox(200, 50, Color.RED); } public void draw(Graphics surface) { surface.drawLine(50, 50, 250, 250); box.draw(surface); } }
  • 6. public class DrawGraphics { BouncingBox box; public DrawGraphics() { // constructor box = new BouncingBox(200, 50, Color.RED); } public void draw(Graphics surface) { surface.drawLine(50, 50, 250, 250); box.draw(surface); } }
  • 7. public class DrawGraphics { public void draw(Graphics surface) { surface.drawLine(50, 50, 250, 250); box.draw(surface); surface.fillRect (150, 100, 25, 40); surface.fillOval (40, 40, 25, 10); surface.setColor (Color.YELLOW); surface.drawString ("Mr. And Mrs. Smith", 200, 10); } }
  • 8. public class DrawGraphics { ArrayList<BouncingBox> boxes = new ArrayList<BouncingBox>(); public DrawGraphics() { boxes.add(new BouncingBox(200, 50, Color.RED)); boxes.add(new BouncingBox(10, 10, Color.BLUE)); boxes.add(new BouncingBox(100, 100, Color.GREEN)); boxes.get(0).setMovementVector(1, 0); boxes.get(1).setMovementVector(-3, -2); boxes.get(2).setMovementVector(1, 1); } public void draw(Graphics surface) { for (BouncingBox box : boxes) { box.draw(surface); } } }
  • 10. What is a good program? Correct / no errors Easy to understand Easy to modify / extend Good performance (speed)
  • 11. Consistency Writing code in a consistent way makes it easier to write and understand Programming “style” guides: define rules about how to do things Java has some widely accepted “standard” style guidelines
  • 12. Naming Variables: Nouns, lowercase first letter, capitals separating words x, shape, highScore, fileName Methods: Verbs, lowercase first letter getSize(), draw(), drawWithColor() Classes: Nouns, uppercase first letter Shape, WebPage, EmailAddress
  • 13. Good Class Design Good classes: easy to understand and use • Make fields and methods private by default • Only make methods public if you need to • If you need access to a field, create a method: public int getBar() { return bar; }
  • 14. Debugging The process of finding and correcting an error in a program A fundamental skill in programming
  • 15. Step 1: Donʼt Make Mistakes Donʼt introduce errors in the first place
  • 16. Step 1: Donʼt Make Mistakes Donʼt introduce errors in the first place • Reuse: find existing code that does what you want • Design: think before you code • Best Practices: Recommended procedures/techniques to avoid common problems
  • 17. Design: Pseudocode A high-level, understandable description of what a program is supposed to do Donʼt worry about the details, worry about the structure
  • 18. Pseudocode: Interval Testing Example: Is a number within the interval [x, y)? If number < x return false If number > y return false Return true
  • 19. Design Visual design for objects, or how a program works Donʼt worry about specific notation, just do something that makes sense for you Scrap paper is useful
  • 21. Step 2: Find Mistakes Early Easier to fix errors the earlier you find them • Test your design • Tools: detect potential errors • Test your implementation • Check your work: assertions
  • 22. Testing: Important Inputs Want to check all “paths” through the program. Think about one example for each “path” Example: Is a number within the interval [x, y)?
  • 23. Intervals: Important Cases Below the lower bound Equal to the lower bound Within the interval Equal to the upper bound Above the upper bound
  • 24. Intervals: Important Cases What if lower bound > upper bound? What if lower bound == upper bound? (hard to get right!)
  • 25. Pseudocode: Interval Testing Is a number within the interval [x, y)? If number < x return false If number > y return false Return true
  • 26. Pseudocode: Interval Testing Is a number within the interval [x, y)? Is 5 in the interval [3, 5)? If number < x return false If number > y return false Return true
  • 27. Pseudocode: Interval Testing Is a number within the interval [x, y)? Is 5 in the interval [3, 5)? If number < x return false If number >= y return false Return true
  • 28. Tools: Eclipse Warnings Warnings: may not be a mistake, but it likely is. Suggestion: always fix all warnings Extra checks: FindBugs and related tools Unit testing: JUnit makes testing easier
  • 29. Assertions Verify that code does what you expect If true: nothing happens If false: program crashes with error Disabled by default (enable with ‐ea) assert difference >= 0;
  • 30. void printDifferenceFromFastest(int[] marathonTimes) { int fastestTime = findMinimum(marathonTimes); for (int time : marathonTimes) { int difference = time - fastestTime; assert difference >= 0; System.out.println("Difference: " + difference); } }
  • 31. Step 3: Reproduce the Error • Figure out how to repeat the error • Create a minimal test case Go back to a working version, and introduce changes one at a time until the error comes back Eliminate extra stuff that isnʼt used
  • 32. Step 4: Generate Hypothesis What is going wrong? What might be causing the error? Question your assumptions: “x canʼt be possible:” What if it is, due to something else?
  • 33. Step 5: Collect Information If x is the problem, how can you verify? Need information about what is going on inside the program System.out.println() is very powerful Eclipse debugger can help
  • 34. Step 6: Examine Data Examine your data Is your hypothesis correct? Fix the error, or generate a new hypothesis
  • 35. Why Use Methods? Write and test code once, use it multiple times: avoid duplication Eg. Library.addBook()
  • 36. Why Use Methods? Use it without understanding how it works: encapsulation / information hiding Eg. How does System.out.println() work?
  • 37. Why Use Objects? Objects combine a related set of variables and methods Provide a simple interface (encapsulation again)
  • 38. Implementation / Interface Library Book[] books; int numBooks; String address; void addBook(Book b) { books[numBooks] = b; numBooks++; } Library void addBook(Book b);
  • 39. Java Interfaces Manipulate objects, without knowing how they work Useful when you have similar but not identical objects Useful when you want to use code written by others
  • 40. Interface Example: Drawing public class BouncingBox { public void draw(Graphics surface) { // … code to draw the box … } } // … draw boxes … for (BouncingBox box : boxes) { box.draw(surface); }
  • 41. Interface Example: Drawing public class Flower { public void draw(Graphics surface) { // … code to draw a flower … } } // … draw flowers … for (Flower flower : flowers) { flower.draw(surface); }
  • 42. public class DrawGraphics { ArrayList<BouncingBox> boxes = new ArrayList<BouncingBox>(); ArrayList<Flower> flowers = new ArrayList<Flower>(); ArrayList<Car> cars = new ArrayList<Car>(); public void draw(Graphics surface) { for (BouncingBox box : boxes) { box.draw(surface); } for (Flower flower : flowers) { flower.draw(surface); } for (Car car : cars) { car.draw(surface); } } }
  • 43. public class DrawGraphics { ArrayList<Drawable> shapes = new ArrayList<Drawable>(); ArrayList<Flower> flowers = new ArrayList<Flower>(); ArrayList<Car> cars = new ArrayList<Car>(); public void draw(Graphics surface) { for (Drawable shape : shapes) { shape.draw(surface); } for (Flower flower : flowers) { flower.draw(surface); } for (Car car : cars) { car.draw(surface); } } }
  • 44. Interfaces Set of classes that share methods Declare an interface with the common methods Can use the interface, without knowing an objectʼs specific type
  • 45. Interfaces: Drawable import java.awt.Graphics; interface Drawable { void draw(Graphics surface); void setColor(Color color); }
  • 46. Implementing Interfaces Implementations provide complete methods: import java.awt.Graphics; class Flower implements Drawable { // ... other stuff ... public void draw(Graphics surface) { // ... code to draw a flower here ... } }
  • 47. Interface Notes Only have methods (mostly true) Do not provide code, only the definition (called signatures) A class can implement any number of interface
  • 48. Using Interfaces Can only access stuff in the interface. Drawable d = new BouncingBox(…); d.setMovementVector(1, 1); The method setMovementVector(int, int) is undefined for the type Drawable
  • 49. Casting If you know that a variable holds a specific type, you can use a cast: Drawable d = new BouncingBox(…); BouncingBox box = (BouncingBox) d; box.setMovementVector(1, 1);
  • 50. Assignment: More graphics Start a new project: code has changed.
  • 51. MIT OpenCourseWare http://ocw.mit.edu 6.092 Introduction to Programming in Java January (IAP) 2010 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.