CIS-260 Home http://www.c-jump.com/bcc/

Anatomy of a class


  1. Anatomy of a class
  2. No concepts exist in isolation
  3. Class Name
  4. Java comments
  5. Attributes
  6. Static Attributes
  7. Constructors revisited
  8. Constructor Examples
  9. Accessor Operations
  10. Private Operations

1. Anatomy of a class


2. No concepts exist in isolation


  • When objects are instantiated, they interact with other objects.

  • Objects may contain other objects, or they can inherit from other objects:

    shape UML diagram

3. Class Name


  • A class name should reflect that a class represents a concept from the application domain.

  • A UML diagram shows classes drawn as rectangles

  • Relationships among classes are drawn as paths connecting class rectangles.

  • A ticket system for a theater has concepts such as

    • tickets, reservations, subscription plans, seat assignment algorithms, and interactive web pages for ordering.

  • Class diagram of a ticket-selling application: uml ticket selling application

4. Java comments


5. Attributes


6. Static Attributes


7. Constructors revisited


8. Constructor Examples


  • 
    public class Point {
        int x;
        int y;
        public Point() {
            x = 0;
            y = 0;
        }
        public Point ( int x, int y ) {
            this.x = x;
            this.y = y;
        }
        public String toString() {
            return x + " " + y;
        }
        public static void main( String[] args )  {
            Point pt = new Point();
            Point pt2 = new Point( 10, 20 );
            System.out.println( pt.toString() );
            System.out.println( pt2.toString() );
        }
    }
    
    
  • To run this example, type command:

        Point.main( null );
    
  • or simply

        java Point
    

9. Accessor Operations


  • Normally, all object attributes are declared private.

  • This prevents objects from accessing other object attributes directly.

  • Such arrangement is dictated by the rules of encapsulation.

  • Accessor operations, known as setters and getters allow sharing appropriate information between objects.

  • For example,

    
    public class Point {
        int x;
        int y;
        public void setX( int x ) {
            this.x = x;
        }
        public  int getX() {
            return x;
        }
        public void setY( int y ) {
            this.y = y;
        }
        public  int getY() {
            return y;
        }
    }
    
    
  • Note: Encapsulation preserves data integrity.

10. Private Operations