Lecture 14
Objects and Classes
Lecture 14 Objects and Classes Object-oriented programming (OOP) - - PowerPoint PPT Presentation
Lecture 14 Objects and Classes Object-oriented programming (OOP) Were always looking for ways to standardize, organize and simplify our code. Objects can help We use objects to represent things in the real world - like a student, a
Objects and Classes
and simplify our code. Objects can help
like a student, a receipt, a hand, etc
same type
redBall ballColor, radius, position fall(), bounce()
lasagne
example
public class Circle { /** The radius of this circle */ double radius = 1; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * Math.PI; } /** Return the perimeter of this circle */ double getPerimeter() { return 2 * radius * Math.PI; } /** Set new radius for this circle */ void setRadius(double newRadius) { radius = newRadius; } }
/** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Construct a circle object */ Circle(double newRadius, int xIn, int yIn){ radius = newRadius; xPos = xIn; yPos = yIn; }
variable
instance of a class
ClassName objectRefVar = new ClassName(); Circle myCircle = new Circle();
redBall.radius)
have a default value, it will be null. Good example are strings
public class TestCircle { public static void main(String[] args) { Circle circle1 = new Circle(); System.out.println("The area of the circle of radius " + circle1.radius + " is " + circle1.getArea()); Circle circle2 = new Circle(25); System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea()); circle2.setRadius(100); System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea()); } }
same way
import java.util.*; public class DateTesting { public static void main(String[] args) { Date date = new Date(); System.out.println(date.toString()); } }
import java.util.*; public class RandomTesting { public static void main(String[] args) { Random rand1 = new Random(3); Random rand2 = new Random(3); Random rand3 = new Random(); for (int i = 0; i < 100; i++){ System.out.println("rand1: " + rand1.nextInt(10)); System.out.println("rand2: " + rand2.nextInt(10)); } // For a new random integer within a range int max = 10; int min = 5; int randomNum = rand3.nextInt((max - min) + 1) + min; System.out.println(randomNum); } }