Essential Object-Oriented Programming Concepts Defined

Posted by Anonymous and classified in Computers

Written on in English with a size of 11.61 KB

Core OOP Definitions

Class and Object

  • Class: A user-defined data structure that binds data members and operations (methods) into a single unit.
  • Object: An instance of a class. Objects are used to perform actions or allow interactions based on the class definition.

Variables and Attributes

  • Method: An action performed using the object's attributes.
  • Attributes: Characteristics or properties of a class. Also known as instance variables (declared outside methods, belonging to one object). They are accessible through static and public methods.
  • Class Variable: Declared using the static keyword; shared among all objects of the class.
  • Local Variables: Declared inside methods, constructors, or blocks; they exist only while the method runs. They cannot be accessed using static or public methods outside their scope, as they are local to the method/block.

Essential Keywords and Modifiers

Access and Behavior Modifiers

  • public: Accessible from anywhere in the program.
  • static: Allows a method or variable to be called without creating an instance of the class.
    • This member belongs to the class itself, not to any particular object (instance).
    • Inside a static method, you do not have access to the current object (this). To call an instance attribute within a static method, you need an object reference.
    • If a variable is a class variable (declared static), it can be accessed without any object reference within a static method.
  • void: Indicates that a method does not return any value.
  • final: Used to make a variable fixed (a constant), or to prevent a class from being subclassed or a method from being overridden.

The 'this' Keyword

  • this: Refers to the current object instance. This is typically used when a parameter name in a method conflicts with an instance variable name.
  • Example of potential error without this: If you write name = name, the assignment often has no effect on the instance variable (e.g., "The assignment to variable modelName has no effect"). The instance variable might remain uninitialized (e.g., null, 0, or 0.0 depending on the type), though the code will still compile and run.

Object Instantiation and Constructors

Creating an Object Instance

Syntax Example:

Lect_Ex11_Vehicle mytesla = new Lect_Ex11_Vehicle();
  • An object named mytesla is created.
  • mytesla is of type Lect_Ex11_Vehicle.
  • The new() keyword creates a new object and invokes a constructor (default or custom) for initialization.

Understanding Constructors

Syntax Example:

public Class_Name() { }
  • A constructor must have the same name as the class.
  • A constructor is not a method and therefore has no return type (you cannot use void, as void is a return type for methods).
  • It is called automatically when you use new() (either the default no-argument constructor or a custom constructor).

Accessing Class Members Across Files

Scenario: Class A (Vehicle) and Class B (Main_File)

To access attributes and methods of Class A (e.g., Vehicle) within Class B (e.g., Main_File), you must create an object instance of Vehicle in Main_File.

  • You cannot directly access declared instance variables/attributes; an object instance is required.
  • To access a static method or variable in Class A from Class B, reference the class name directly (instead of an object instance).
    Example: ClassA.method().

Method and Constructor Overloading

Overloading Definition

Overloading allows you to reuse the same method name (or constructor name) by defining several methods with different numbers or types of input parameters (signatures).

Constructor Overloading Example

int Year;
String Name;
double Weight;

public Tut13_ConstructorOverloading(int year) {
    Year = year;
}

public Tut13_ConstructorOverloading(int year, String name) {
    Year = year;
    Name = name;
}

public Tut13_ConstructorOverloading(int year, String name, double weight) {
    Year = year;
    Name = name;
    Weight = weight;
}

Handling Multiple Objects

To create and process multiple objects efficiently, you typically use constructors and arrays or collections.

  1. Define a constructor, e.g., Tut15_MultipleObjs(String brandname, String type) {}.
  2. Create an array (or list) of that object type:
    Tut15_MultipleObjs[] MyObjects = new Tut15_MultipleObjs[4];
  3. Initialize each object within the MyObjects array.

References: Arrays and ArrayLists

For detailed information on arrays and dynamic lists, refer to the following topics:

Arrays (Lect_Ex16_aboutArrays)

  • Note: You cannot simply call the array name (e.g., frenzArray) to print the entire array content directly.

ArrayLists (Lect_Ex17_aboutArrayList)

  • The ArrayList class is a resizable array found in the java.util package.
  • ArrayList uses methods (e.g., .add(), .get()) rather than operators.
  • Elements stored in an ArrayList are objects. Remember that String in Java is an object, not a primitive type.
  • To use primitive types (like int or double) in an ArrayList, you must use their equivalent wrapper classes (e.g., Integer or Double).

Related Tutorials

  • Tut_14_LongWordFinder
  • Lab0 and Lab1

OOP Principles and Object Relationships

Data Encapsulation

  • Allows controlled access to members and methods, typically by using the private access modifier.
  • Hides internal representations (implementation details) from outside access.

Object Interactions

Inter-class communication achieved via object references and accessor methods (Getters and Setters).

  1. Class B declares certain private variables.
  2. Class B provides public accessor methods for each private member:
    public 'Return Type' get_membername() {}
    public void set_membername(arg) {}
  3. Class A defines a public method that accepts an object of Class B (Object Reference):
    public void interactWithB(Tut22b_ClassB objB)
    Class A then uses the accessors (get() and set()) methods to access and modify objB's instance variables.
  4. The Main class creates instances of both A and B, and passes object B into object A's interaction method.

Object Composition (Strong "Has-a" Relationship)

One class contains references to other class objects as instance variables. The contained object (the part) is usually created and owned by the container (the whole), meaning its lifetime depends on the container.

Example: A Car has an Engine, and the Car controls the Engine's creation.

  1. Define the Part Class (e.g., Engine) with variables, methods, constructor, and accessors.
  2. Define the Whole Class (e.g., Car):
    1. Declare an Engine class instance variable as a private variable. (Only Car controls how the Engine is used.)
    2. Create the Engine object inside the Car constructor. (This enforces Encapsulation: the Car class decides how its engine is built.)
    3. Note: If you create the Engine object during variable declaration, it limits flexibility. Creating it in the constructor allows for unique initialization per object.
  3. The Main Class creates a Car instance and calls car-related methods.

Object Aggregation (Loose "Has-a" Relationship)

One class has a reference to another class, but the lifetime of the contained object is independent of the container. The part is created outside and passed in, potentially shared between multiple objects.

Example: A Car has an Engine, but the Engine might exist independently or be shared.

  1. Define the Part Class (e.g., Engine) with variables, methods, constructor, and accessors.
  2. Define the Whole Class (e.g., Car):
    1. Declare an Engine class instance variable as a private variable.
    2. Define the Car constructor to accept an Engine object as an input parameter.
    3. In the constructor, assign the passed Engine object to the Engine instance variable declared in class variables.
  3. The Main Class handles object creation:
    1. Create an Engine instance first.
    2. Create a Car instance and pass the created Engine instance as a parameter.

Access Modifiers in OOP

Access modifiers determine the visibility or access level of variables, methods, constructors, or classes to other parts of the code.

Private Access (Enforcing Encapsulation)

Private members can only be accessed within the same class.

Private Variables

  • Variable values can be set and reset within the same class.
  • In a different class, a private variable is not accessible, even if you create an object of that class. You cannot use dot notation like obj.private_var_name1.
  • To allow controlled access from different classes, you must provide public get() and set() methods (accessors).

Private Methods

  1. Declare your class and its instance variables (including private ones).
  2. Write constructors and public methods. Use these public methods as entry points to call and utilize the private methods internally.
  • There is no other way to call a private method directly when you are in another class, even by creating and using objects of the defining class.

Access Level Summary Table

ModifierAccess LevelSame ClassSame PackageSubclass (Different Package)Anywhere (Different Package)
publicAnywhere in the programYesYesYesYes
privateONLY within same classYesNoNoNo
protectedSame package and subclassesYesYesYesNo
default (No Modifier)Within same packageYesYesNoNo

Related entries: