Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Welcome back CS02 students
- please log in to your VM
- https://vm.ktbyte.com
- username: 16fa + ktbyte_username
- password: ktbyte
- Today's lesson: inheritance review, interfaces
- */
- import java.util.*;
- // public class is a class that is visible to other files
- public class Lesson4 {
- // a public function/method is something that can be
- // accessed outside of the class
- public static void main(String[] args) {
- Point p = new Point(2, 5);
- System.out.println(p.getX());
- System.out.println(Point.getCount()); // static function
- Point p2 = new LabeledPoint(-5, 10, "KTByte office");
- System.out.println(p2.getX()); // -5
- System.out.println(Point.getCount()); // 2
- // Object class has a toString() that you can override
- // to change what this displays
- System.out.println(p); //
- System.out.println(p2); // (-5, 10)
- // also look up: boolean equals(Object o) inside Object
- Point[] points = {p, p2, new Point(3, -4)};
- System.out.println(Arrays.toString(points));
- Arrays.sort(points); // sort based on the compareTo method
- System.out.println(Arrays.toString(points));
- }
- }
- // we cannot access private functions/variable inside Point
- class LabeledPoint extends Point {
- private String label;
- public LabeledPoint(int x, int y, String label) {
- super(x, y); // calls the super classes' constructor
- this.label = label;
- }
- public String toString() {
- return label + ": " + super.toString();
- }
- }
- // represents a point on a 2D plane
- // once a Point is created, its x y values cannot be modified
- class Point implements Comparable<Point> {
- // private means classes outside of Point
- // cannot access it
- private int x;
- private int y;
- // counts the number of Point objects created
- // static means the variable is shared across all Point object
- private static int count = 0;
- // static function can be called without a Point object
- public static int getCount() {
- return count;
- }
- // force it so that when you create a Poitn object
- // you have to set x and y
- public Point(int x, int y) {
- // "this" means the current object
- this.x = x;
- this.y = y;
- count++;
- }
- public int getX() {
- return x;
- }
- public int getY() {
- return y;
- }
- public String toString() {
- return "(" + x + ", " + y + ")";
- }
- // look up: Comparable
- // point with a lower x value comes first
- public int compareTo(Point p) {
- return x - p.x;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement