1 / 97

Method Overloading Review

Method Overloading Review. Method Overloading (1/4 ). Can define multiple methods of same name within a class, as long as method signatures are different Example: java.lang.Math static method max takes in two numbers and returns the greater of the two

hova
Download Presentation

Method Overloading Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Method Overloading Review

  2. Method Overloading (1/4) • Can define multiple methods of same name within a class, as long as method signatures are different • Example: java.lang.Math • static method max takes in two numbers and returns the greater of the two • There are actually three max methods-- one for ints, one for floats, one for doubles // this is an approximation of what Math’s // three max methods look like public class Math { // other code elided public static int max(int a, int b) { // return max of two ints } public static float max(float a, float b) { // return max of two floats } public static double max(double a, double b){ // return max of two doubles } }

  3. Method Overloading (2/4) • Methods in same class with same name but different parameter lists • When callingan overloaded method, Java infers which method you mean based on parmeter list • Thus cannot have two methods with identical signatures but different return types—compiler error becauseJava can’t determine which to call! // this is an approximation of what Math’s // three max methods look like public class Math { // other code elided public static int max(int a, int b) { // return max of two ints } public static float max(float a, float b) { // return max of two floats } public static double max(double a, double b){ // return max of two doubles } }

  4. Method Overloading (3/4) • Be careful not to confuse overloading and overriding! • override an inherited method in a subclass: the signatures (name; number, types, and order of parameters) must be the same • overload methods in the same class: names are same, but signatures must be different // this is an approximation of what Math’s // three max methods look like public class Math { // other code elided public static int max(int a, int b) { // return max of two ints } public static float max(float a, float b) { // return max of two floats } public static double max(double a, double b){ // return max of two doubles } }

  5. Method Overloading (4/4) • If neither overriding nor overloading: Can use same name, indeed signatures for methods in different classes • Java can differentiate by type of instance on which method is called during method resolution • for example: if classes Car and Dog both have a move method that takes in one parameter of type int, Java knows to use the Dog’s move when called on an instance of Dog: • Dog dog = new Dog(); • Car car = new Car(); • dog.move(1); //Dog’s move method is called. • car.move(1); //Car’s move method is called.

  6. Method Overloading: Constructors • Even constructors can be overloaded! Wardrobe class has multiple constructors • A String (java.lang.String) is a sequence of alphanumeric characters, including space! • Example: String s = “CS15 Rocks!”; • Can use System.out.println to print any string you want: System.out.println(s); public class Wardrobe { private String _top; private String _bottom; public Wardrobe(String top, String bottom) { _top = top; _bottom = bottom; } public Wardrobe(String top) { _top = top; _bottom = “Jeans”; } public Wardrobe() { _top = “T-Shirt”; _bottom = “Jeans”; } }

  7. Method Overloading: Example • An overloaded method can call other overloaded methods • public class Plastic { • public Plastic(BurnBookmyBurnBook) { • DirtySecret secret = myBurnBook.getDirtySecret(); • this.backStab(secret); • } • public void backStab(DirtySecret secret) { • String victim = secret.getVictim(); //find out whose secret it is • this.backStab(victim, secret); • } • public void backStab(String victim, DirtySecret secret) { • //code to backstab elided (we don’t teach you how to backstab!) • } • //other methods elided • }

  8. Lecture 9 Intro to Swing 0 of 88

  9. What is Swing? • Swing is an API (Application Programming interface) • part of core Java library • used to create applications with 2D graphics • Frequently used classes in javax.swing package • javax.swing.JFrame– the main window used by your app • javax.swing.JPanel-- a canvas that contains graphical components • javax.swing.JButton-- a clickable button JFrame JPanel JButtons 1 of 88

  10. Creating Applications from Scratch • Until now, TAs took care of graphical components for you • Support code created JFrame, JPanels, all graphical components • From now on, you’re in charge of this! 2 of 88

  11. Graphical User Interfaces (GUIs) • GUIs provide a user-controlled (i.e., graphical) way to send messages to a system of objects • You’ll use Swing to create your own GUIs throughout the semester 3 of 88

  12. Pixels and Coordinate System X (0, 0) • The screen is a grid of pixels (tiny dots) • Integer Cartesian plane with: • origin in upper-left corner • y-axis increasing downward • corresponds to Latin-based languages’ writing order Y 4 of 88 pixels

  13. Pixels and Coordinate System X (0, 0) • When working with Swing, you’ll be able to set the size and location of different components (panels, buttons, etc.) in pixels • The “location” of each component will be the location of its top left corner Y 5 of 88 pixels

  14. Creating GUIs with Swing • Pattern: instantiate the Swing components you need and add them to graphical containers • Start with JFrame JFrame JPanel JLabel Hello, World! • Add JPanelto JFrame JButtons • Add JButtons, JLabels, etc. to JPanel 6 of 88

  15. Creating GUIs with Swing • Swing uses a default layout to arrange components in a JFrameor JPanel • We’ll learn how to customize layout later in lecture • For now, let Swing do it for us JFrame JPanel JLabel Hello, World! JButtons 7 of 88

  16. Our First Swing Application JFrame • Spec: app that contains text reading “CS15 Rocks!” and button that randomly changes the text’s color with every click • Useful classes: JFrame, JPanel, JLabel, JButton, and ActionListener JLabel JPanel JButton 8 of 88

  17. DEMO: ColorTextApp JFrame JLabel JPanel JButton 9 of 88

  18. Process JFrame • Create a top-level App class that contains an instance of JFrame • Create a subclass of JPanelthat contains an instance of JButtonand an instance of JLabel • Add an instance of your JPanelsubclass to the JFrame • Set up an ActionListenerthat changes the label’s color each time the button is clicked JLabel JPanel JButton 10 of 88

  19. Top-level Class: ColorTextApp • This is our top-level class • It contains the JFrame(window in which the app will display) as a component public class ColorTextApp { • public ColorTextApp() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args) { new ColorTextApp(); } } 11 of 88

  20. Top-level Class: ColorTextApp • First we instantiate a JFrame, which we store in local variable frame • Note: these slides will omit import statements at top of file public class ColorTextApp { • public ColorTextApp() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args) { new ColorTextApp(); } } 12 of 88

  21. Top-level Class: ColorTextApp • Next we call setDefaultCloseOperationon our JFrame • This method specifies what happens when user hits “x” in corner of the JFrame • Pass in constant JFrame.EXIT_ON_CLOSEas an argument so app will quit when we press the “x” • Swing magic keeps JFrames and their contents alive as long as the “x” is not pressed, so they will not be “garbage- collected!” (Java GC’s variables when they go out of scope – cease to exist) public class ColorTextApp { • public ColorTextApp() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args) { new ColorTextApp(); } } 13 of 88

  22. Top-level Class: ColorTextApp • Finally, we call the method setVisibleon our JFrame • Pass in booleanvalue trueas an argument • This makes the JFrameshow up! • Pro tip: Always call this method last to avoid nasty layout bugs public class ColorTextApp { public ColorTextApp() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String[] args) { new ColorTextApp(); } } 14 of 88

  23. Process JFrame • Create a top-level App class that contains an instance of JFrame • Create a subclass of JPanel that contains an instance of JButton and an instance of JLabel • Add an instance of your JPanel subclass to the JFrame • Set up an ActionListener that changes the label’s color each time the button is clicked JLabel JPanel JButton 15 of 88

  24. JPanelSubclass: ColorTextPanel • The class ColorTextPanel“is a” JPanel: our canvas that may contain other Swing GUI components • We’ve specialized this class to contain and display a JLabeland a Jbutton (local vars) public class ColorTextPanel extends JPanel { public ColorTextPanel() { JLabel label = new JLabel("CS15 Rocks!"); JButton button = new JButton("Random Color"); Dimension panelSize = new Dimension(150, 75); this.setPreferredSize(panelSize); this.add(label); this.add(button); } } 16 of 88

  25. JPanelSubclass: ColorTextPanel First, we instantiate a JLabel and JButton In each case, we pass in a String as an argument This String is the text we want the label/button to display Here we pass the string as a “literal”; could also pass a string variable public class ColorTextPanel extends JPanel { public ColorTextPanel() { JLabel label = new JLabel("CS15 Rocks!"); JButton button = new JButton("Random Color"); Dimension panelSize = new Dimension(150, 75); this.setPreferredSize(panelSize); this.add(label); this.add(button); } } 17 of 88

  26. JPanelSubclass: ColorTextPanel • Now we set the “preferred size” of our panel • First, instantiate a Dimension(object that represents a width and height, in pixels) • First argument is width, second is height • Then call method setPreferredSizeon panel, passing in the Dimensionas an argument public class ColorTextPanel extends JPanel { public ColorTextPanel() { JLabel label = new JLabel("CS15 Rocks!"); JButton button = new JButton("Random Color"); Dimension panelSize = new Dimension(150, 75); this.setPreferredSize(panelSize); this.add(label); this.add(button); } } 18 of 88

  27. The ColorTextPanelclass • Finally, we add the label and button to the panel by calling the panel’s addmethod • This is a necessary step for the label and button to show up! public class ColorTextPanel extends JPanel { public ColorTextPanel() { JLabel label = new JLabel("CS15 Rocks!"); JButton button = new JButton("Random Color"); Dimension panelSize = new Dimension(150, 75); this.setPreferredSize(panelSize); this.add(label); this.add(button); } } 19 of 88

  28. Process JFrame • Create a top-level App class that contains an instance of JFrame • Create a subclass of JPanel that contains an instance of JButton and an instance of JLabel • Add an instance of your JPanel subclass to the JFrame • Set up an ActionListener that changes the label’s color each time the button is clicked JLabel JPanel JButton 20 of 88

  29. The ColorTextAppclass public class ColorTextApp { public ColorTextApp() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); JPanel panel = new ColorTextPanel(); frame.add(panel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new ColorTextApp(); } } • First, instantiate a new ColorTextPanel • Then, add it to the JFrameby calling the addmethod • Finally, call the method packon the JFrame • “pack” tells frame to resize itself based on the preferred sizes of the components inside it 21 of 88

  30. Process JFrame • Create a top-level App class that contains an instance of JFrame • Create a subclass of JPanel that contains an instance of JButton and an instance of JLabel • Add an instance of your JPanel subclass to the JFrame • Set up an ActionListener that changes the label’s color each time the button is clicked JLabel JPanel JButton 22 of 88

  31. Responding to User Input • Need a way to respond to stimulus of button being clicked • We refer to this as event handling • A source generates an event (like a mouse click or a key press) and notifies all registered listeners • Each listener has a method for responding to the event • stimulus-response mechanism that allows multiple listeners to respond 23 of 88

  32. ActionListeners • Whenever a JButtonis clicked, it generates a java.awt.event.ActionEvent • We define class that listens for ActionEvents: must implement interface java.awt.event.ActionListener • ActionListenerinterface declares method: public void actionPerformed(ActionEvent e); • This method must be defined in our listener class • called by Java whenever an ActionEvent is fired • specifies response to event 24 of 88

  33. ActionListeners ActionListener ActionEvent e JButton Click! public void actionPerformed( ) { • // Respond here; may or may not use ActionEvent // (print something to the console, // tell a JLabel to change color, etc.) } ActionEvent e 25 of 88

  34. Our ActionListener: ColorListener • Our listener class is ColorListener • Its job is to listen for ActionEvents and respond to them by changing the color of a JLabel public class ColorListener implements ActionListener { • private JLabel _label; //associated label public ColorListener(JLabel label) { _label = label; } @Override public void actionPerformed(ActionEvent e) { int red = (int) (Math.random()*256); int green = (int) (Math.random()*256); int blue = (int) (Math.random()*256); Color random = new Color(red, green, blue); _label.setForeground(random); } } 26 of 88

  35. Our ActionListener: ColorListener • Associated with a JLabel, which it refers to as _label-- a ColorListenerwill be passed the JLabelwhose color it should change • When ActionEventis detected, will change _label’s color public class ColorListener implements ActionListener { private JLabel _label; public ColorListener(JLabel label) { _label = label; } @Override public void actionPerformed(ActionEvent e) { int red = (int) (Math.random()*256); int green = (int) (Math.random()*256); int blue = (int) (Math.random()*256); Color random = new Color(red, green, blue); _label.setForeground(random); } } 27 of 88

  36. Our ActionListener: ColorListener • actionPerformeddefines response to ActionEvent • In this case, we want it to generate a random color, and then set _labelto that color public class ColorListener implements ActionListener { private JLabel _label; public ColorListener(JLabel label) { _label = label; } @Override public void actionPerformed(ActionEvent e) { int red = (int) (Math.random()*256); int green = (int) (Math.random()*256); int blue = (int) (Math.random()*256); Color random = new Color(red, green, blue); _label.setForeground(random); } } 28 of 88

  37. Our ActionListener: ColorListener • Use Math.random()to generate three random ints 0-255 • Use them as RGB values for a new Color • Call JLabelmethod setForegroundon _labelto set its color to the random color we’ve created public class ColorListener implements ActionListener { private JLabel _label; public ColorListener(JLabel label) { _label = label; } @Override public void actionPerformed(ActionEvent e) { int red = (int) (Math.random()*256); int green = (int) (Math.random()*256); int blue = (int) (Math.random()*256); Color random = new Color(red, green, blue); _label.setForeground(random); } } 29 of 88

  38. Adding ActionListeners public class ColorTextPanel extends JPanel { public ColorTextPanel() { JLabel label = new JLabel("CS15 Rocks!"); JButton button = new JButton("Random Color"); ColorListener listener = new ColorListener(label); button.addActionListener(listener); Dimension panelSize = new Dimension(150, 75); this.setPreferredSize(panelSize); this.add(label); this.add(button); } } • First, instantiate a ColorListener • Pass in label as argument to listener’s constructor so it knows to change label’s color • Next, use method addActionListener to add our ColorListener to button • Typical pattern: listeners are added to the event-emitting component they listen to • Whenever button emits an ActionEvent, listener will hear and respond to it 30 of 88

  39. Process JFrame • Create a top-level App class that contains an instance of JFrame • Create a subclass of JFrame that contains an instance of JButton and an instance of JLabel • Add a JPanel to the JFrame • Set up an ActionListener that changes the label’s color each time the button is clicked JLabel JPanel JButton 31 of 88

  40. public class ColorTextPanel extends JPanel { public ColorTextPanel() { JLabel label = new JLabel("CS15 Rocks!"); JButton button = new JButton("Random Color"); ColorListener listener = new ColorListener(label); button.addActionListener(listener); Dimension panelSize = new Dimension(150, 75); this.setPreferredSize(panelSize); this.add(label); this.add(button); } } The Whole App public class ColorTextApp { public ColorTextApp() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); JPanel panel = new ColorTextPanel(); frame.add(panel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new ColorTextApp(); } } public class ColorListener implements ActionListener { private JLabel _label; public ColorListener(JLabel label) { _label = label; } @Override public void actionPerformed(ActionEvent e) { int red = (int) (Math.random()*256); int green = (int) (Math.random()*256); int blue = (int) (Math.random()*256); Color random = new Color(red, green, blue); _label.setForeground(random); } } 32 of 88

  41. Putting It All Together ColorTextApp JFrame ColorTextPanel JButton JLabel ColorListener 33 of 88

  42. Logical vs. Graphical Containment JFrame ColorTextApp JLabel JFrame ColorTextPanel JPanel JButton • Graphically, the ColorTextPanelis contained within the JFrame, but logically, both are contained together in a top-level Appclass; App and ColorListener aren’t graphic! • Logical containment is based on where objects are created, while graphical is based on swing elements being added to other swing elements via the add(…) method • Note: The JButton also has a reference to ColorListener, but this reference is omitted from our diagram to avoid excessive complexity. JButton JLabel ColorListener 34 of 88

  43. Another Swing App: Clock • Specifications: App should display the current date and time, updating every second • Useful classes: JFrame, JPanel, JLabel, Timer, ActionListener JFrame JPanel JLabel 35 of 88

  44. DEMO: Clock 36 of 88

  45. Using Timers • The class javax.swing.Timercomes in handy when we need to perform a task repeatedly at regular intervals • When we instantiate a Timer, we pass it: • An int(number of milliseconds between Timerticks) • An ActionListenerthat should be notified when the Timeremits an ActionEvent(on every tick) • We’re going to use a Timerto update the time displayed on our JLabelat regular intervals 37 of 88

  46. Using Timers ActionListener ActionEvent e Tick! Timer ActionEvent e public void actionPerformed( ) { // Respond to ActionEvent here! // (print something to the console, tell // a JLabel to update its text, etc.) } 38 of 88

  47. Process: Clock • Create top-level class that contains a JFrame • Write a subclass of JPanelthat contains a JLabel. Add an instance of it to our JFrame • Write a class that implements ActionListener-- it should know about a JLabeland update its text on every ActionEvent • Instantiate a listener and a Timer, and start the Timer JFrame JPanel JLabel 39 of 88

  48. Top-level Class: Clock • As in the previous example, we create a top-level class that contains a JFrame • Specify closing behavior of JFramethe same way we did last time public class Clock { public Clock() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new Clock(); } } 40 of 88

  49. Top-level Class: Clock • Call packon the JFrameso it will resize itself based on its contents (which we’ll be adding soon) • Last, make the frame show up by calling “setVisible(true); ” public class Clock { public Clock() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new Clock(); } } 41 of 88

  50. Process: Clock • Create top-level class that contains a JFrame • Write a subclass of JPanel that contains a JLabel. Add an instance of it to our JFrame • Write a class that implements ActionListener -- it should know about a JLabeland update its text on every ActionEvent • Instantiate a listener and a Timer, and start the Timer JFrame JPanel JLabel 42 of 88

More Related