Spaces:
Running
Running
| A class is defined by the class identifier. | |
| As stated earlier, all code in Java must be written inside classes. | |
| However, not all the code that is written is directed at the objects that are created from the class. | |
| In Java, the class name must be exactly the same as the file name. | |
| Specifically, a file must have a public class defined by its name. | |
| For example, the file Car.java must have a class definition of | |
| public class Car | |
| ...and from the file OwnFineClass.java definition | |
| public class OwnFineClass | |
| You can write MORE THAN 1 CLASS in the SAME FILE, but ONLY 1 can be PUBLIC. | |
| The others are initialized without the public attribute. | |
| A class has different features. Features can be public or private. | |
| When an object is created from a class, the client of the object has direct access to the public features. | |
| The client in this context is the program code through which the entity is accessed | |
| (it does not mean, for example, the program user or any other physical person). | |
| ==================================================================================================================================================== | |
| Attributes | |
| Let's start by looking at the attributes of the class (note the two t's). | |
| An attribute is a variable of an object. | |
| They are therefore used to define the information content of the objects that make up the class. | |
| Each object in a class has its own values for all the attributes defined in the class. | |
| As an example, consider a class that models a student. | |
| The class has three attributes: name, student number and credits: | |
| public class Student { | |
| // Attributes are usually defined at the start of the class | |
| String name; | |
| String studentId; | |
| int studyPoints; | |
| } | |
| ATTRIBUTES are thus defined inside the class, but OUTSIDE ANY METHODS. | |
| Typically, attribute variables are assigned values in the CONSTRUCTOR based on PARAMETERS YOU PASS IN. | |
| So let's write a constructor for the Student class: | |
| public class Student { | |
| // Attributes are usually defined at the start of the class | |
| String name; | |
| String studentId; | |
| int studyPoints; | |
| // Constructor | |
| public Student(String n, String id, int sp) { | |
| name = n; | |
| studentId = id; | |
| studyPoints = sp; | |
| } | |
| } | |
| Now new student objects can be created using the new operator: | |
| public class Testclass { | |
| public static void main(String[] args) { | |
| Student sally = new Student("Sally Student", "12345", 10); | |
| Student sam = new Student("Sam Student", "99999", 35); | |
| } | |
| } | |