CS62 - Spring 2020 - Class 4
Example code in this lecture
Inheritance
Graphics
GraphicalCard
Lecture notes
admin
- quiz!
- how did the lab go?
- we will send some basic feedback soon about your submissions
- assignment 1 out later today and due on Tuesday
- if you struggled on the lab, come see us!
inheritance revisited
- we can build a new class that is an extension of another class
- the original class is said to be the superclass (or parent class) and the new class the subclass (or child class)
- to do this, in the class header, you use the keyword "extends", e.g.
public class B extends A{
...
}
- the subclass:
- inherits all public methods from the superclass
- e.g. given an object of type B, we can call any method that A had on B
- can access any instance variables that are declared public *or* protected
- can call any methods that are declared as public *or* protected
- additions in the subclass
- you can then add any additional instance variables and methods in the subclass
- these will be available normally in the subclass, but NOT in the superclass
- if you define a method with the same "signature" as in the superclass, it will override it
Look at
Inheritance code
- We have a class called A that has a private and protected instance variable
- Two public methods
- B is a class that inherits from A
- we indicate this with the keyword "extends"
- B has all of the instance variables of A
- however, it can only access those that are protected or public
- in the resetInt method, we can access number
- if we tried to access the text variable, we would get an error
Variable type
- the type of a variable defines what methods we can call on the associated object:
A blah = ...;
// some code
// What methods can I call on blah?
- only the public methods of A
- Why is it ok to assign a B object to a variable of type A?
- A blah = new B(...);
- What methods can we call on blah?
- only the public methods of A?
- Does B have all of those methods?
- Yes!
- Will they have the same functionality as A's public methods?
- not if B overrode them, i.e., wrote a method with the same type signature
look at test2 in the B class in
Inheritance code
- Why can't I call a.resetInt()
- Java can't guarantee that there will be an object of type B in there, so it can't know that it's a safe call
look at test3 in the B class in
Inheritance code
- What will be printed out?
A1: I'm an A
B1: I'm a B
A2: I'm a B
- Since A2 references an object of type B, then B's toString method gets called!
- When the methods are called, they are based on the object
the Java class hierarchy
- *everything* in Java is a subclass of some class (except for 1 class in Java)
- you can only inherit from one class
- if you don't inherit from a class, by default, you inherit from the class Object
- Object has a toString method (which is why it's always available!)
- You can see the object hierarchy at:
http://docs.oracle.com/javase/7/docs/api/overview-tree.html
look at the shape package in the
Inheritance code
- The Shapes class defines basic behavior
- The Square and Rectangle classes extend the Shape class
- they both override the getArea method
- they both add methods particular to the class
look at ShapeMaker class in
Inheritance code
- What does the getShapes method do?
- prompts the user for a number
- then prompts them for that number of shapes
- if the user enters a rectangle or square it creates one
- otherwise creates a generic shape
- Where does it store these shapes?
- in an ArrayList of Shapes
- Why does that work?
- Rectangles and Squares are both shapes!
- What does the printShapes method do?
- goes through the Shape ArrayList and prints each shape out (i.e. calls the toString method)
Graphics/GUIs in Java
- A way to represent windows and things that go inside windows
- can be a bit tedious, but not particularly complicated
- makes heavy used of inheritance
look at BasicGraphics class from
Graphics code
- The basic window is called a JFrame (imported from javax.swing:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html
)
- It's a top-level window with a title and a border
- We can add things to the inside of this frame
- It has a single constructor that takes a string
- What does 'super("this is my awesome title")' do?
- call the JFrame constructor. You can always look at the documentation if you need to:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html
- What do you think the other four lines in the constructor do?
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set it so that if you click close, the window actually closes
setSize(500, 300); // set the size of the window
setLocation(100,100); // set the location of the window
setVisible(true); // make it visible
- by default windows/frames are not visible, so this last line is critical
look at BasicGraphics2 class from
Graphics code
- All these set methods are public methods and can either be called in the class or externally. Either way is fine for this class.
look at MyGraphicsDemo class from
Graphics code
- The JFrame is a container that we can add stuff to
- Use constants!
- constructor
- graphic objects are not displayed when they are created. They must be drawn in the paint() method using the Graphics object.
- For most of the graphics objects there is both a float version and a double version
- Line2D.Double
- Line2D.Float
- The only differences is whether the coordinates are specified as floats or doubles
- Graphic objects in java are laid out based on an x and y coordinate system starting with 0, 0 at the top left corner of the window
- positive x is right
- positive y is down
- See the JavaDoc online for details for these classes
- Line2D.Double
- Ellipse2D.Double
- Rectangle.Double
paint(Graphics g) method
- the key method for drawing graphics
- invoked implicitly whenever another object calls this frame’s repaint() method or whenever the screen manager requires it, e.g. when a portion of this frame is revealed by the movement of another frame
- The Graphics object passed in gives us a handle on an object to actually display on the screen
- First thing to do is typecast the Graphics object as a Graphics2D object
- Until we "draw" an object using the Graphics2D class, it won't be displayed
- draw - to draw any Shape object we've created (like a line, rectangle or ellipse)
- drawString - For putting text on the screen
- fill - fills the interior of the shape
- Attributes like line color, fill color and font are NOT set at the Shape object level, but are set on the Graphics2D object before it is used to draw the Shape object
interfaces
- There are two main ways we can indicate shared behavior. The first is through inheritance.
- The second is through interfaces. Interfaces define methods that a class must define. E.g.,
public interface InterfaceName{
public void method1();
public int method2(int number);
public ArrayList<String> anotherMethod(String myString);
}
- A class can then "implement" these methods by adding "implements" in the class definition:
public class A implements InterfaceName{
}
- we must then implement ALL of the methods described in the interface, or our code will not compile
- Why might this be useful?
- interfaces define a type, i.e., we can declare variables and parameters of that type
- allows us to group objects together with similar functionality
- public void example(InterfaceName obj){...}
- we know that we can call any methods defined in the interface from that object
- we can say, the only thing that's important to me is that the class implement method x, y and z
Handling mouse events
- Two commonly used interfaces:
- MouseListener (
https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html
)
- for taking actions based on mouse presses, releases, clicks, enters and exits
- MouseMotionListener (
https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseMotionListener.html
)
- for taking actions based on mouse moves or drags
- moving/dragging is continuous in the real world. How does this translate to method calls?
show MouseEvents class in
Graphics code
- beginning code in main is the generic code to setup a frame
- private classes
- you can only have ONE public class in a file
- however, you can have private helper classes
- we'll see these frequently in this class
- again, useful for compartmentalizing functionality
- the MouseEventsHelper class implements both the MouseListener interface and MouseMotionListener class
- notice that if you comment out one of the methods, the compiler will complain, because you have not satisfied your contractual obligation of the interface
- each method is passed a MouseEvent object giving some information about the mouse event that triggered/called the method
- we'll use the getX() and getY() method to get the x and y coordinates of the event
private classes
- you can only define one high-level class per file
- sometime it can be helpful to have another class in a file that is only used internally
- these are called private classes
- private classes are not accessible outside of the outer class
- they're common for doing things like providing support for handling mouse events
run MouseEvents class
look at GraphicalCard class in
GraphicalCard code
- extends Rectangle2D
- constructor
- makes a card at x, y with a fixed with and size dependent on the number of the card
- getColor
- red or black
look at BasicCardDisplay class in
GraphicalCard code
- just draws our GraphicalCard (in this case, 11 of diamonds
- we construct the card in the constructor
- then draw it with fill in the paint method
look at CardDisplay class in
GraphicalCard code
- instead of a single card, generate multiple cards (save them in an ArrayList)
- in paint, paint all of the cards
look at MoveableCard class in
GraphicalCard code
- extends GraphicalCard
- this is the power of inheritance!!!
- only add a moveCard method
- setFrame is an inherited method from Rectangle2D which changes the location and size
look at MoveableCardDisplacy class in
GraphicalCard code