Object-Oriented Programming Fundamentals
Comp 241, Fall Example Colored points on the screen What data goes into making one? Coordinates Color What should a point be able to do? Move itself Report its position
Comp 241, Fall
4 Java Terminology Each point is an object Each includes three fields Each has three methods Each is an instance of the same class
Comp 241, Fall Object-Oriented Style Solve problems using objects: little bundles of data that know how to do things to themselves Not the computer knows how to move the point, but rather the point knows how to move itself Object-oriented languages make this way of thinking and programming easier
public class Point { private int xCoord; private int yCoord; public Point() { xCoord = 0; yCoord = 0; } public int currentX() { return xCoord; } public int currentY() { return yCoord; } public void move (int newXCoord, int newYCoord) { xCoord = newXCoord; yCoord = newYCoord; }
public class PointTest{ public static void main( String args[]) { Point firstPoint; Point secondPoint; firstPoint = new Point(); secondPoint = new Point(); firstPoint.move(15, 25); secondPoint.move(35, 45); System.out.println(“The first point is at x = “ + firstPoint.currentX() + “ and y = “ + firstPoint.currentY() ); System.out.println(“The second point is at x = “ + secondPoint.currentX() + “ and y = “ + secondPoint.currentY()); }
Comp 241, Fall Objects and Variables Variables Local variables Variable types Type defines what set of values variable can take, i.e., its domain Two kinds of types in Java Primitive types: int, boolean, char, float, double, short, long, byte All other types are sets of objects java.* (e.g. java.lang, java.util, etc.) define some useful types String, Vector, … Other types we define ourselves
Comp 241, Fall Type Hierarchy public class Point { private int xCoord; private int yCoord; … } public class ColoredPoint extends Point { … private int color; public int getMyColor() { return color; } public class LabelledColoredPoint extends ColoredPoint { private String label; public String getMyLabel() { return label; }
Comp 241, Fall Overriding Methods public class Point { private int xCoord; private int yCoord; … public void printMyself() { System.out.print(“my x = “ + xCoord + “my y = “ + yCoord ); } public class ColoredPoint extends Point { private int color; … public void printMyself() { super.printMyself(); System.out.print(“ “ + “my color = “ + color); }