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
Course.studentNumber = 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( ); Course.studentNumber = 1;
course1.courseCode= new String(“CSC112“);
course1.studentName= new String(“Majed AlKebir“);
//Create and assign values to course2
course2 = new Course( ); Course.studentNumber ++;
course2.courseCode= new String(“CSC107“);
course2.studentName= new String(“Fahd AlAmri“);
System.out.println(course1.studentName + " has the course “+
course1.courseCode + “ ” + course1.studentNumber);
System.out.println(course2.studentName + " has the course “+
course2.courseCode + “ ” + course2.studentNumber);
}
}
Page 6 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP