Cours 2 Java PDF
Document Details
Uploaded by SecureLesNabis775
Badji Mokhtar University - Annaba
2024
Dr. Sarra Namane
Tags
Summary
This document is a lecture on Java programming, focusing on classes and objects. It discusses the concept of classes, objects, methods, and constructors in the context of object-oriented programming using Java examples.
Full Transcript
Chapter 2: Classes and objects Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Constituting a Class of Objects In practice, an OO programmer spends more time making classes than thinking...
Chapter 2: Classes and objects Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Constituting a Class of Objects In practice, an OO programmer spends more time making classes than thinking about what will happen to the objects when they run. So, instead of calling it "object-oriented programming," it might be better to call it "class-oriented programming"! Before working with objects, they need a data structure that links their attributes to the methods that can access them. Every object is created from a class and must follow that class's rules throughout its life. In real life, objects can change roles (like a student becoming a teacher), but in object-oriented programming, objects are restricted by their class. A class is a strict model that an object must follow, similar to how a house follows a blueprint. A class is described by three key pieces of information. 2 The Three Constituent Parts of a Class Every class definition includes three pieces of information: first, the name of the class, then its attributes and their types, and finally, its methods. In this example: - Class Name: `Car` - Attributes: `make` (String), `model` (String), `year` (int) - Methods: `start()` and `stop()`, both of which print messages to the console. 3 Definition of a Class Method: With or Without Return A method returns something if the body of its instructions ends with an expression such as `return x`. If this is the case, its name will be preceded by the type of value it returns. In this example: - Class Name: Rectangle; - Attributes: length(double), width (double); - Methods: - printDimensions(): Prints the dimensions of the rectangle (does not return a value, `void`). - `calculateArea()`: Returns the area of the rectangle (returns a `double`). 4 Comments `` encloses comments within code. For single-line comments, `//` can also be used. Any text written as a comment is ignored by the code. We will use comments extensively in our code to explain it without altering its execution. 5 Functions and Procedures In procedural programming, a function usually returns a value, like mathematical functions such as f(x). A procedure does not return a value; it just performs actions to change data. Similarly, a method in programming can take arguments (values given to it) and use them in its execution. Example: ✔ printProduct(int number1, int number2): A method that prints the product of two numbers without returning a value. Method arguments Arguments in a method let you change how the method works based on the values you provide. This is like how `x` changes the output in a mathematical function f(x). 6 Identification and Overloading of Methods by Their Signature A method's signature consists of its name and the list/type of its arguments. Communication between objects relies on matching method signatures. Each signature is uniquely linked to the method's instructions. The signature is a way to access the method's instructions. Method overloading occurs when a method has the same name but a different argument list or type. 7 Identification and Overloading of Methods by Their Signature (2) Here is a simpler example using a `Calculator` class: The add(int a, int b) method adds two integers. The add(int a, int b, int c) method is an overload that adds three integers. It has the same name but a different argument list. The add(double a, double b) method is another overload that adds two decimal numbers. It differs from the first method by the type of its arguments. - The last commented-out method would be forbidden because it has the same signature as the first method add(int a, int b) but a different return type, which would make the methods indistinguishable when called. Overloading creates a new method with a different signature. The version of the method called depends on the number and type of arguments. 8 The Class as a Functional Module: Differentiating Objects by Attribute Values 1. A class eliminates the need to define the number and type of attributes and methods for each object. 2. This efficiency is especially useful when dealing with many objects from the same class. 3. Object-oriented programs often manage many objects of the same class, like "cars" or "pedestrians.“ 4. Objects are stored in collections, which can be expandable (lists) or fixed (arrays). 5. Objects of the same class differ only by their attribute values. 6. The constructor method is used to set the initial values of an object's attributes during its creation. 9 The Constructor A constructor is a special method that has the same name as the class and no return type. It initializes the attributes of an object when it is created. Unlike other methods, a constructor is only called during object creation. It's recommended to always define your own constructor, even if it mimics the default one. Constructors are often overloaded based on the known attribute values at object creation. If no constructor is defined, a default one is provided, but once you define one that takes arguments, you must define another without arguments if needed. Object creation involves calling the constructor, which sets the initial values for the object's attributes. 10 The default constructor A default constructor is a no-argument constructor automatically provided by the Java compiler if no constructors are explicitly defined in a class. It initializes the object's attributes to their default values (e.g., `null` for objects, `0` for integers). If you define any constructor in your class, the default constructor is not provided by the compiler, so you must define it manually if needed. Example: 11 Different constructors 12 Different constructors (2) In this updated version, the constructor argument names (`carBrand`, `carModel`, `carYear`) are different from the class attribute names (`brand`, `model`, `year`). - This helps distinguish between the parameters passed to the constructor and the class’s attributes, which is useful for clarity in larger projects or when the constructor logic is more complex. The output will remain the same as in the previous example, displaying the details of the `Car` objects created with different constructors. 13 The Class as a Guarantee of Proper Use 1. Dependency on Class: Objects rely entirely on their class for creation and manipulation, ensuring consistency in what they can do. 2. Role of the Compiler: In languages like Java, C++, and C#, the compiler ensures that nothing unexpected happens during execution by strictly enforcing what the class defines. 3. Strong Typing: These languages are strongly typed, meaning they prevent sending messages (method calls) to objects that aren’t defined in their class, reducing runtime errors. 4. Scripted Languages: Languages like Python and PHP 5 skip the compilation step, leading to faster development but higher risks of runtime errors. 5. Execution vs. Compilation: While skipping compilation saves time, it increases the risk of encountering errors during execution, sometimes when it's too late to fix them. 14 Strongly Typed Language A programming language is considered strongly typed when the compiler ensures that objects and variables are only used in ways that are allowed by their type. This verification increases the reliability of the program's execution. Java, C++, and C# are strongly typed languages where the compilation step is crucial. This is not the case, with Python and PHP 5. 15 Strongly Typed Language (2) In this example, the line number = text; would cause a compilation error, as Java does not allow assigning a string (String) to a variable of type integer (int). This demonstrates the principle of strong typing, where the compiler enforces strict rules on type usage. 16 Dynamic Memory vs. Static Memory 1. Static Memory: Early programming languages reserved memory at the start of the program, and the program only modified existing data. This is known as static memory management. 2. Stack Memory: A controlled memory space where data is managed in a last-in, first-out manner based on the instruction blocks. This is a type of static memory management. 3. Dynamic Memory: Introduced with the `new` keyword, it allows memory to be allocated during program execution and places new variables or objects anywhere in memory, without being tied to instruction blocks. 17 Dynamic Memory vs. Static Memory (2) 4. C++ Example: In C++, objects can be created without `new`, meaning they are placed in a memory area managed like stack memory. 5. References and Heap Memory: With dynamic memory, references store the physical address of objects, which can be placed anywhere in memory. Managing these objects, particularly their disappearance, requires special consideration. 6. Challenges in Dynamic Memory: Managing dynamic memory is more complex, as objects don't follow the strict structure of stack memory, requiring careful handling to avoid errors like memory leaks. 18 Class Memory and Object Memory ❑ Class Memory vs. Object Memory: ✔ Passive Part: Attributes specific to each object. ✔ Active Part: Methods common to all objects of the class. ❑ Static Attributes: ✔ Attributes shared by all objects of a class. ✔ Stored in the class's memory space, not in individual object memory spaces. ❑ Efficiency: Storing shared attributes in class memory is more efficient than storing them with each object. 19 Class Methods vs. Instance Methods ❑ Instance Methods: Operate on objects and are called on specific instances. ❑ Static Methods: Belong to the class itself and can be called without creating an object. Example: Java’s `Math` class uses static methods for mathematical operations. ❑ `main()` Method: In Java and C#, it's static and used to start the program. ❑ Static Data: Static methods use static data, which is shared across all instances of the class. 20 Class Methods vs. Instance Methods (2) 21 Static ❑ Static attributes of a class that are common to all objects and are directly associated with the class itself, as well as methods that can be executed directly from the class, are declared as static. They can be used without creating any objects. These attributes are shared by all instances of the class and associated directly with the class. ❑ A static method can only use static attributes and can only call other static methods. These methods can be called directly from the class, without needing an instance. 22 Classes, Files, and Directories ❑ Class Organization: - Classes and Packages: In object-oriented programming, classes with similar responsibilities or functionalities are grouped into packages. For example, if you have several classes that handle mathematical operations, you might group them in a package named `math`. 23 Classes, Files, and Directories (2) ❑ File Organization: - Files and Directories: Similarly to classes, files are organized into directories. Each Java source file is usually named after the class it contains. Files are grouped into directories that correspond to packages. Example: project/ └── src/ └── math/ ├── Calculator.java └── AdvancedCalculator.java 24 Natural and Dynamic Linking of Classes ❑ Natural Link: - Method Calls Between Classes: When you have a class A that uses class B, you can simply call methods from B in A. This link is naturally handled by the compiler without needing additional configuration at the operating system level. In this example, the `Application` class uses the `Calculator` class to perform an addition. No special configuration is needed for `Application` to use `Calculator`. 25 Natural and Dynamic Linking of Classes (2) ❑ Dynamic Link: - Compilation and Execution: In Java, classes are dynamically linked during compilation and execution. If the `Application` class needs to use `Calculator`, the Java compiler ensures that `Calculator` is accessible and correctly linked at compile time. At runtime, Java automatically loads the necessary classes. - Example: When you compile and run the above Java code, Java ensures that the `Calculator` class is available and correctly linked so that the `add` method can be called from `Application`. 26 Learning exercise 1. Why can a static method only access static attributes and methods? 2. Why is it important for the file name to match the class name in Java when containing the `main` method? Explain how this requirement affects the compilation and execution of the program. 3. In what situations would you use method overloading? Discuss how method overloading can enhance the flexibility and readability of your code. 4. Explain the concept of a constructor in Java. How does constructor overloading work? Describe the role of constructors in object creation and how overloading can be used to initialize objects in different ways. 5. What is the significance of the `main` method in Java, and why must it be declared `public` and `static`? Discuss the role of the `main` method as the entry point of a Java application 27 Learning exercise answer 1. Why can a static method only access static attributes and methods? Answer: A static method can only access static attributes and methods because it operates at the class level, not at the instance level. This means it doesn’t have access to instance-specific data or methods. ✔ Cannot Access Instance Data: Static methods cannot access or modify instance variables (attributes) directly because they do not operate on a specific object. ✔ Cannot Call Instance Methods: They cannot call instance methods directly since these methods require an object to operate on. ✔ Only Access Static Data: They can only access static variables and other static methods within the class. ✔ No this Keyword: They cannot use the this keyword, which refers to the current instance of the class. 28 Learning exercise answer (2) 2. Why is it important for the file name to match the class name in Java when containing the `main` method? Explain how this requirement affects the compilation and execution of the program. Answer: In Java, the file name must match the public class name containing the main method to ensure proper organization and accessibility. This requirement helps maintain a consistent file structure, as the Java compiler needs to match public class names with file names for successful compilation. If the names don't match, the compiler will produce an error, and the JVM won't be able to locate and execute the main method. This convention ensures that each public class is correctly compiled and executed, promoting clarity and preventing runtime issues. 29 Learning exercise answer (3) 3. In what situations would you use method overloading? Discuss how method overloading can enhance the flexibility and readability of your code. Answer: Method overloading in Java allows you to define multiple methods with the same name but different parameters (i.e., different parameter lists). This feature enhances flexibility and readability in various situations: Different Parameters: Allows methods with the same name but different parameter lists (types, numbers) to be defined, enabling operations on various types of data or numbers of arguments. Flexibility: Provides the ability to handle diverse use cases with the same method name, improving versatility in method implementation. Readability: Enhances code readability by using consistent method names for similar operations, making the code easier to understand and maintain. Default Behavior: Facilitates providing default settings or behaviors while allowing customization through overloaded methods. Simplified Maintenance: Reduces the need for multiple method names, avoiding naming conflicts and simplifying code management and updates. 30 Learning exercise answer (4) 4. Explain the concept of a constructor in Java. How does constructor overloading work? Describe the role of constructors in object creation and how overloading can be used to initialize objects in different ways. Answer: Constructor Definition: Name: Must match the class name. No Return Type: Does not have a return type. Automatic Invocation: Called automatically when an object is created with the new keyword. Role of Constructors: Initialization: Sets initial values for an object's attributes. Setup: Performs necessary setup operations for the object. Constructor Overloading: Multiple Constructors: Allows defining multiple constructors with different parameter lists in the same class. Different Initializations: Each constructor can initialize the object in a different way based on the provided parameters. Flexibility: Provides various ways to create and set up objects, accommodating different 31 initialization scenarios. Learning exercise answer (5) 5. What is the significance of the `main` method in Java, and why must it be declared `public` and `static`? Discuss the role of the `main` method as the entry point of a Java application. Answer: Significance of the main Method Entry Point of the Application: The main method is the starting point of a Java application. It is where the Java Virtual Machine (JVM) begins execution of the program. Without a main method, the JVM will not have a designated starting point for running the application. Application Execution: When you run a Java application, the JVM looks for the main method in the class specified in the command line or configuration. It then executes this method to start the application’s execution. Why the main method must be public and static Public Modifier: The main method must be public so that it can be accessed by the JVM from outside the class. Since the JVM needs to call this method to start the application, it must be publicly accessible. Static Modifier: The main method is static because it needs to be called by the JVM without creating an instance of the class. Since it’s a class-level method, it can be invoked directly from the class itself, not requiring an object instance. 32 References BERSINI, Hugues. La programmation orientée objet. Editions Eyrolles. 2010. Head First Java, Second Edition, By Kathy Sierra, Bert Bates, O'Reilly Media. Programmer en JAVA, 4ème édition, Deitel et Deitel, Les éditions Reynal Goulet. http://java.sun.com Le Programmeur JAVA 2, Lemay L, Campus Press. Au cœur de Java 2 Volume I - Notions fondamentales, Horstmann et Cornell, The Sun Microsystems Press Java Series. Programmer en Java, Claude Delannoy, Eyrolles. 33