Your SlideShare is downloading. ×
Java i lecture_3
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Java i lecture_3

29
views

Published on

Published in: Technology, Art & Photos

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
29
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • Transcript

    • 1. Java I--Copyright © 2000 Tom Hunter
    • 2. Java I--Copyright © 2000 Tom HunterChapter 3Introduction to Java Applets
    • 3. Java I--Copyright © 2000 Tom Hunter• There is no main method in a Java Applet.• A Java Applet can only run in a browser.• An Applet is run only when an HTML page requeststhat it be executed.• In place of a browser, we use a utility called theappletviewerThis is a “minimal browser”—it ignores all other HTMLcommands except the one used to run an Applet.Applets Execute in a Browser
    • 4. Java I--Copyright © 2000 Tom Hunterappletviewer syntax.• To execute an Applet, do the following:Compile your Java Applet using javac, as usual.C: javac Hello.javaCreate an HTML file and name it: Example.htmlApplets Execute in a Browser<HTML><APPLET CODE=“Hello.class” WIDTH=300 HEIGHT=40></APPLET></HTML>To run the Applet, you type the following:C: appletviewer Example.htmlThese parameters refer to the widthand height (in pixels) of the box your Appletwill get when it is executed on a web page.w
    • 5. Java I--Copyright © 2000 Tom HunterWriting A “String” (A Sentence) using an Applet• Because an Applet gets help from a browser, it containsmuch less code.• The most obvious omission is the main method.A Simple Applet
    • 6. Java I--Copyright © 2000 Tom Hunter• Every Java Applet must commence by importing theclass JApplet.• This class does all the heavy lifting for us.A Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;
    • 7. Java I--Copyright © 2000 Tom HunterA Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;• We are also importing class Graphics from the awt(Abstract Windowing Tools) package so that we can drawthe String on the Applet.
    • 8. Java I--Copyright © 2000 Tom Hunter• All code in an Applet sits in the wrapper of a class.• Likewise, the class name starts with a Capital• The public keyword enables the browser to create aninstance of this class—what we have to do by ourselvesin an Application.A Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;public class WelcomeApplet extends JApplet{}
    • 9. Java I--Copyright © 2000 Tom Hunter• Take special note of the “extends” keyword.• extends means that our WelcomeApplet isbuilding on top of another class, JApplet !• We’re taking everything it has, and adding to it !A Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;public class WelcomeApplet extends JApplet{}This is Inheritance—a very special principle—andthere are special terms to describe the relationship.Superclass (base class) JAppletSubclass (derived class) WelcomeAppletw
    • 10. Java I--Copyright © 2000 Tom Hunter• Now we have added a method called paint.• Notice its Access Modifier is public, so this methodcan be called by any object outside of this class.• The return value is void.A Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;public class WelcomeApplet extends JApplet{public void paint( Graphics g ){}}
    • 11. Java I--Copyright © 2000 Tom Hunter• Apparently, the paint method of JApplet expects to bepassed an object of type Graphics.• We are instantiating (creating) a Graphics class objectcalled g right there, inside the parenthesis of paint.A Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;public class WelcomeApplet extends JApplet{public void paint( Graphics g ){}}Don’t get nervous. When you created an integervariable ( int x; char m; ) you were doingthe same thing, “Creating a instance of a type.”“ Graphics g ” is creating an example orinstance of Graphics class and naming that instance g.w
    • 12. Java I--Copyright © 2000 Tom Hunter• Finally, with this statement, we use the Graphics classobject g, and call the method drawString that allGraphics class objects have.• drawString expects a String, plus two coordinatesthat say where to place the bottom-left corner of the text.A Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;public class WelcomeApplet extends JApplet{public void paint( Graphics g ){g.drawString( “Welcome to Java!”, 25, 25 );}}
    • 13. Java I--Copyright © 2000 Tom Hunter• Class JApplet already has a method called paint.Class JApplet’s paint method is empty. It does nothing.• Although we did inherit the do-nothing method paintfrom JApplet, ours will do something.A Simple Applet// A First Appletimport javax.swing.JApplet;import java.awt.Graphics;public class WelcomeApplet extends JApplet{public void paint( Graphics g ){g.drawString( “Welcome to Java!”, 25, 25 );}}
    • 14. Java I--Copyright © 2000 Tom HunterOverriding a method• This process is central to inheritance.• Although we received a perfectly good method from theSuperclass, we decided to create our own version of it—with the exact same name.• Since we used the same name, our version of themethod takes over or overrides the method.• We haven’t affected the original copy of the method—itstill exists—we just improved upon it in our own specialSubclass.Applets Execute in a Browser
    • 15. Java I--Copyright © 2000 Tom Hunter• You might have to resize the Applet. You set thedimensions of this box in your Example.html file.• Note: When you resize the Applet, you trigger the paintmethod to fire.Applets Execute in a Browser
    • 16. Java I--Copyright © 2000 Tom Hunter• In an Application, the method main is guaranteed to becalled by the operating system.• In an Applet, which has no main method, three othermethods are guaranteed to be called by the operatingsystem:init()start()paint()( In that order )More About Applets
    • 17. Java I--Copyright © 2000 Tom Hunter• Since we did not override init()and start(),the default versions of these methods were executed.• What did they do? Nothing!• Only paint() did something because we overrode itand made it do something useful.• Finally, anytime you resize an Applet (meaning drag thebottom right corner to make it bigger or smaller), then themethod paint() is automatically called again.More About Appletsinit() start() paint()
    • 18. Java I--Copyright © 2000 Tom Hunter• Attributes and Behaviors: All Objects havethem.• An Object in the real world has:Attributes--its qualities, and itsBehaviors--what it does.Thinking About ObjectsObject:A balloonAttributes:Color: redDiameter: 2 inchesBehaviors:RisesInflatesDeflatesPops
    • 19. Java I--Copyright © 2000 Tom Hunter• Java is based on the unit of a class.A class is an object, it encapsulates the attributes andbehaviors into one self-contained unit.• The attributes (internal data variables) and behaviors(methods that have an effect on those internal datavariables) are combined into a unit called an object.Java encapsulates data (attributes) andmethods (behavior)into a unit called anObject.Thinking About Objects
    • 20. Java I--Copyright © 2000 Tom HunterThinking About Objects• Some objects are Similar—Java TakesAdvantage of the SimilaritiesA bicycle inner tube is a specific type of balloon.It has a color and a width.It inflates, deflates and pops.I cannot change the diameter of the balloon withoutusing the method of inflating it.Alone, I can’t change the diameter attribute of theinner tube. I have to use the method of inflating ordeflating the inner tube to change its diameter attribute.We say the width attribute is hidden. I can’tchange it without using the method.
    • 21. Java I--Copyright © 2000 Tom HunterThinking About Objects• An Employee is an ObjectA Generic Employee has attributes:nameaddressphone_numbersocial_security_numberA Generic Employee has a method:calculate_pay
    • 22. Java I--Copyright © 2000 Tom HunterThinking About Objects• An Employee is an ObjectAn Hourly Employee is a specific kind of Employee.It has the same Attributes as the Generic Employee,plus other Attributes:hourly_pay_rateovertime_hoursAn Hourly Employee has the same method:calculate_paybut the calculation is different.It uses hourly_pay_rate and overtime_hours.
    • 23. Java I--Copyright © 2000 Tom HunterThinking About Objects• An Employee is an ObjectA Salaried Employee is specific kind of Employee.It has all the same Attributes as the Generic Employee, plusanother Attribute:salaryA Salaried Employee has the same method:calculate_paybut the calculation is different.It uses salary.
    • 24. Java I--Copyright © 2000 Tom HunterThinking About Objects• An Employee is an ObjectA Commission Employee is specific kind ofEmployee.It has all the same Attributes as the Generic Employee, plusother Attributes:base_paycommission_rateA Commission Employee has the same method:calculate_paybut the calculation is different.It uses base_pay and commission_rate.
    • 25. Java I--Copyright © 2000 Tom HunterThinking About Objects• An Employee is an ObjectA Piecework Employee is specific kind of Employee.It has all the same Attributes as the Generic Employee, plusanother Attribute:pay_per_pieceA Piecework Employee has the same method:calculate_paybut the calculation is different.It uses pay_per_piece.
    • 26. Java I--Copyright © 2000 Tom HunterThinking About ObjectsInheritance•The Hourly Employee, Salaried Employee, CommissionEmployee and Piecework Employee all...Inherit the Attributes and Behaviors of the GenericEmployee.They elaborate on the stuff they inherited.Any Superclass methods that are appropriate are NOToverridden.Although they inherit from Generic Employee, the base isnot changed.
    • 27. Java I--Copyright © 2000 Tom Hunter• The Graphics class that drew the String on our previousApplet has many methods at our disposal.• To the list of API classes we must know, we must nowadd Graphics and JApplet.Draw A Line
    • 28. Java I--Copyright © 2000 Tom Hunter• This will put lines above and below the sentence.• The 4 arguments are the beginning and end points of theline.Draw A Line// Display Text and Linesimport javax.swing.JApplet;import java.awt.Graphics;public class WelcomeLines extends JApplet{public void paint( Graphics g ){g.drawLine( 15, 10, 210, 10 );g.drawLine( 15, 30, 210, 30 );g.drawString( “Welcome to Java!”, 25,25);}}
    • 29. Java I--Copyright © 2000 Tom Hunter• This is the output.Draw A Line
    • 30. Java I--Copyright © 2000 Tom Hunter• This will produce the same result as we achieved withthe Addition Application, only this time as an Applet.• The goal is to add two floating-point numbers.Applet Example: Addition
    • 31. Java I--Copyright © 2000 Tom Hunter// Add two floating point numbersimport javax.swing.*;import java.awt.Graphics;public class AdditionApplet extends JApplet{double sum; // instance variablepublic void init(){}public void paint( Graphics g ){}}wNotice, this variable sum isoutside of any method.sum is an instance variable.Numeric instance variables areautomatically initialized to zero,char instance variables areautomatically initialized to spacesand boolean are automaticallyinitialized to false.This asterisk allows you toimport all the classes in a package.( But only the classes at thisdirectory, not any sub-directories. )Also, from that wildcardpackage, the compiler willonly bring in those classes thatyou actually used in the program.Two Kinds of Java Variables:Instance variables:• Declared outside of any method• Automatically initialized• Visible in all methods of the classLocal variables:• Declared inside a method• Not automatically initialized—a syntax error if youtry to use them with out first putting a value in.• Vanish after the method returns to whatever called it.
    • 32. Java I--Copyright © 2000 Tom Hunter// Add two floating point numbersimport javax.swing.*;import java.awt.Graphics;public class AdditionApplet extends JApplet{double sum; // instance variablepublic void init(){String firstNumber, secondNumber; // local variablesdouble num1, num2; // local variables}public void paint( Graphics g ){}}
    • 33. Java I--Copyright © 2000 Tom Hunter// Add two floating point numbersimport javax.swing.*;import java.awt.Graphics;public class AdditionApplet extends JApplet{double sum; // instance variablepublic void init(){String firstNumber, secondNumber;double num1, num2;firstNumber = JOptionPane.showInputDialog(“First Num” );secondNumber = JOptionPane.showInputDialog(“Second Num” );num1 = Double.parseDouble( firstNumber );num2 = Double.parseDouble( secondNumber );sum = num1 + num2;}public void paint( Graphics g ){}}Since num1 and num2 are doubles, weuse the “Type Wrapper” class that canconvert a String into a double.( There are Type Wrapper classes for allthe primitive data types. )w
    • 34. Java I--Copyright © 2000 Tom Hunter// Add two floating point numbersimport javax.swing.*;import java.awt.Graphics;public class AdditionApplet extends JApplet{double sum; // instance variablepublic void init(){String firstNumber, secondNumber;double num1, num2;firstNumber = JOptionPane.showInputDialog(“First Num” );secondNumber = JOptionPane.showInputDialog(“Second Num” );num1 = Double.parseDouble( firstNumber );num2 = Double.parseDouble( secondNumber );sum = num1 + num2;}public void paint( Graphics g ){g.drawRect( 15, 10, 270, 20 );g.drawString( “The Sum is ” + sum, 25, 25 );}}• In drawRect, the parameters are the coordinatesfor the top left-hand corner, the width and the height.
    • 35. Java I--Copyright © 2000 Tom HunterApplet Example: Addition Output
    • 36. Java I--Copyright © 2000 Tom HunterAnother Word on Variables• Earlier, we discussed the so-calledprimitive variables.The are so named, because they are not objects.For short, these are called just variables.int num1; double sum;
    • 37. Java I--Copyright © 2000 Tom HunterAnother Word on Variables• There is another group—reference variables.These are objects.String firstNumber;String secondNumber;The identifiers for these reference variables only containreferences—that is, the addresswherethis reference variable can be found in memory.
    • 38. Java I--Copyright © 2000 Tom Hunternum100000000 00000000 00000000 00000132• int num1 = 132; [Integers always take 4 bytes.]A primitive can only store one piece of data.7045607{This is the actual place in memory where the String Object stores everything it needs toaccomplish its task as a String Object. Inevitably, it would be a lot more than a simple primitive...firstNumber00000000 00000000 07045607A Referenceis apointer !• String firstNumber = JOptionPane.showMessageDialogfirstNumber is a reference (pointer) to the real Object.An object can store many kinds of data.