60 likes | 119 Views
Public / Private & Dynamic /Static.
E N D
Public / Private & Dynamic /Static • Beginners should not worry about public/private differences. Just make everything public or unspecified. (Switch from unspecified to public if the compiler complains.) Later, after you become more proficient, you can start using private for the sake of the encapsulation tenets of good software engineering. • Main() needs to be declared static. The reason for this is that when we execute Intro, we are not creating any instances of it, so that main() must be a class method. If we had any other methods in Intro, we would have to make them static too.
Void vs non void • Computing a sales commission given the sales amount and the commission rate Answer: non-void method with return type double • Printing a calendar for a month Answer: void method • Computing a square root Answer: non-void method with return type double • Testing whether a number is even and return true if it is Answer: non-void method with return type boolean • Printing a message for a specified number of times Answer: void method • Computing the monthly payment, given the loan amount, number of years, annual interest rate. Answer: non-void method with return type double. • Finding the corresponding uppercase letter given a lowercase letter. Answer: non-void method with return type char.
class Car { String licensePlate; // e.g. "New York 543 A23" double speed; // in kilometers per hour double maxSpeed; // in kilometers per hour }
class CarTest { public static void main(String args[]) { Car c = new Car(); c.licensePlate = "New York A45 636"; c.speed = 70.0; c.maxSpeed = 123.45; System.out.println(c.licensePlate + " is moving at " + c.speed + " kilometers per hour."); } }
class Circle{ /** The radius of this circle */ double radius = 1.0; /** 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 * 3.114159; } }
public class TestCircle1 { public static void main(String[] args) { Circle myCircle = new Circle(5.0); System.out.println("The area of the circle of radius " + myCircle.radius + " is " + myCircle.getArea()); Circle yourCircle = new Circle(); System.out.println("The area of the circle of radius " + yourCircle.radius + " is " + yourCircle.getArea()); yourCircle.radius = 100; System.out.println("The area of the circle of radius " + yourCircle.radius + " is " + yourCircle.getArea()); } }