CS 162 Lecture-Module #03:
Basics of Working with Classes, Objects, and Methods in Java


lab #1 was intended to give you hands-on experience
with classes, objects, and methods;
here, I'll discuss their specifications ~~more 'officially' (;-)

in lab #1 you used :  Circle,  Square, and  Triangle
you made  of them:   circle1,  circle2,  square1,  square2, etc.
and you  their :  moveRight(),  moveDown(),  makeInvisible(), etc.

programs have classes to organize
specifically to keep together related data and operations

"instance" is a term usable beyond computer science
e.g. "instance of concept chair"
each instance
    has its own copy of coordinates  xPosition  and  yPosition,  diameter,  color, etc.
methods such as  moveRight()  and  changeColor()  must refer to one instance's  xPosition,  color, etc.

convention: names of classes are uppercase, and all other names in Java
(objects, methods, fields, locals, ...) are lowercase




what's the structure of the source code for all this in a class?
public class name {
    fields a.k.a. instance variables a.k.a. attributes
        /* each object which is an instance of this class
         *   has its own copies of these class instance-variables
         *   to store information about itself --- e.g. its position
         */
    
    methods
    }
separate class(es) in separate  .java  file(s)
e.g.  Circle.java,  Square.java,  Picture.java, ...

field

method

method: block of code for doing something with an object
    e.g. draw self , move object's position ,
        change an instance variable ,
        initialize object — constructor method

special
initializing method called a
"constructor"
---------------
name of this method same as class name
no separate return-type (not even  void)
typically sets instance-variables
invoked with  new  ...
e.g.
    Circle sun;
    sun = new Circle();

a class isn't really required to have a constructor
it's just usually prudent to set instance-variables

otherwise access anything (e.g. a method) of an object via the "." operator:
    object-namemethod-call

so method-call accesses instance-variables of the specified object
e.g.  sun.moveRight();
    changes  x,y  variables of only object  r;
        x,  y  of other objects (of this class) not changed
        (rem. each object has own copies of instance-variables such as color)

method needs qualifier  public  to be usable thus




summary of this lecture-module

basics of classes, objects, and methods:


(Copyright © 2009 by Hugh McGuire   — for thoughts about this, see   http://www.cis.gvsu.edu/~mcguire/teaching/copyright_thoughts.html .)