09-26-2013

posted Sep 26, 2013, 7:36 AM by Samuel Konstantinovich   [ updated Sep 26, 2013, 12:50 PM ]
Consider a Python like program that follows. How would a Java style program like it be arranged? How can we encapsulate parts into classes? Which parts would go into which class and why?

#globals
Ax=3,Ay=10
Bx2=9,By=32
r1 = 4.3
r2 = 9.0

#functions
def distanceAB():
    ...

def distanceToZero(a,b)
    ...

def area(r)
    ...

def volume(r)
    ...

#main function
def main():
    ...
    ...
    ...

The Coordinate class from today:

public class Coordinate{
    private double x,y;
   
    //default constructor has no parameters, 
    //You may leave it out, but then all values become zero/null
    public Coordinate(){
x = 0.0;
y = 0.0;
    }

    //constructor that allows you to set the x and y
     public Coordinate(double q, double r){
x = q;
y = r;
    }

    //Methods to access information (Accessors)
    public double getX(){
return x;
    }

    public double getY(){
return y;
    }

    //Methods to change things (Mutators)
    public void setX(double a){
x = a;
    }
    public void setY(double a){
y = a;
    }
    
    public void setXY(double ex,double why){
x = ex;
y = why;
    }

    //the overridden toString method:
    public String toString(){
return "("+x+","+y+")";
    }

    /*
    The three distance methods:
    */

    //distance to 0,0
    public double distance(){
return Math.sqrt( x*x + y*y );
    }

    //distance to a manually entered Coordinate
    public double distance(double a,double b){
return Math.sqrt( Math.pow(x-a,2)+Math.pow(y-b,2));
    }

    //distance to another Coordinate
    public double distance(Coordinate P){
return Math.sqrt( Math.pow(x-P.x,2)+Math.pow(y-P.y,2));
    }
}



Comments