Chapter 3: Introduction to
Classes and Objects
Class attributes
Class and Instance Attributes
• Instance attributes (and methods) are:
• associated with an instance (object) of the class.
• and accessed through an object of the class.
• each object of the class has its own distinct copy of
instance attributes (and methods)
• Class attributes (and methods):
• live in the class
• can also be manipulated without creating an instance of the
class.
• are shared by all objects of the class.
• do not belong to objects’ states.
Page 2 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP
Class Attributes and Objects
• A class attribute is in one fixed location
in memory.
• Every object of the class shares class
attributes with the other objects.
• Any object of the class can change the
value of a class attribute.
• Class attributes (and methods) can also
be manipulated without creating an
instance of the class.
Page 3 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP
Class Attributes Declaration
• The class attributes (and methods) are
declared as instance attribute but with
the static modifier in addition.
<modifiers> <data type> <attribute name> ;
Modifiers
Modifiers Data
DataType
Type Name
Name
public static int studentNumber ;
Page 4 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP
Class Attributes Access
• Class attributes (and methods) can also
be manipulated without creating an
instance of the class.
<class name>.<attribute name>
Class
ClassName
Name Attribute
AttributeName
Name
[Link] = 0 ;
Page 5 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP
class Course {
// attributes
public String studentName;
public String courseCode ;
public static int studentNumber;
}
public class CourseRegistration {
public static void main(String[] args) {
Course course1, course2;
//Create and assign values to course1
course1 = new Course( ); [Link] = 1;
[Link]= new String(“CSC112“);
[Link]= new String(“Majed AlKebir“);
//Create and assign values to course2
course2 = new Course( ); [Link] ++;
[Link]= new String(“CSC107“);
[Link]= new String(“Fahd AlAmri“);
[Link]([Link] + " has the course “+
[Link] + “ ” + [Link]);
[Link]([Link] + " has the course “+
[Link] + “ ” + [Link]);
}
}
Page 6 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP