3.3 Anatomy of a Class
1. Exam Points
public variables or methods can be accessed from external classes.
private variable or methods can not be accessed from external classes.
Instance variables(non-static) and methods(non-static) must be accessed using an instance name.
Class variables (static) and methods(static) can be accessed using the class name.
Classes will all be declared public in this course.
Constructors will all be declared public in this course.
Note:
- Be careful when reading a question, which variable or method is public or private.
- If an attribute is unique to each object(radius), declare it as instance variable.
- If an attribute is shared by all objects(pi) of a class, declare it as class variable.
2. Knowledge Points
(1) Anatomy of a Class
- Inside a class, you can define:
Attributes: represented by variables.
Behaviors: represented by methods.
- That means we can
encapsulate(封装) data and behaviors in a class.
- Example: a Student class encapsulates data and behaviors of student objects, while a Dog class encapsulates data and behaviors of dog objects.

(2) Data Encapsulation
Data encapsulation(数据封装) is a technique in which the implementation details of a class are kept hidden from external classes.
- The keywords
public and private affect the access of classes, data, constructors, and methods.
- The keyword
private restricts access from external classes.
- The keyword
public allows access from external classes.
Access to attributes (data) should be kept internal to the class in order to accomplish encapsulation.
- Therefore, it is good programming practice to designate the instance variables for these attributes as private unless the class specification states otherwise.
- Example: declare instance variables as private, and allows accessing them using public methods.

- Access to behaviors (methods) can be internal or external to other classes.
- Methods designated as public can be accessed internally or externally to a class.
- Methods designated as private can only be accessed internally to the class.
- Example: public and private methods.

(3) Note
In this course
- classes are always designated public.
- constructors are always designated public.
- instance variables (non-static) belong to the object, and each object has its own copy of the variable.
- class variables (static) belong to the class, all the objects of the class share the same copy of the variable.
- instance methods are non-static.
- class methods are static.

3. Exercises