Java Object Classes
# Java Objects and Classes
As an object-oriented programming language, Java supports the following fundamental concepts:
1. **Class**:
* Defines the blueprint for objects, including attributes and methods.
* Example: `public class Car { ... }`
**2. Object**:
* An instance of a class, possessing state and behavior.
* Example: `Car myCar = new Car();`
**3. Inheritance**:
* A class can inherit the attributes and methods of another class.
* Example: `public class Dog extends Animal { ... }`
**4. Encapsulation**:
* Making an object's state (fields) private and accessing it through public methods.
* Example: private String name; public String getName() { return name; }
**5. Polymorphism**:
* Objects can take on multiple forms, primarily achieved through method overloading and method overriding.
* Example:
* Method Overloading: `public int add(int a, int b) { ... }` and `public double add(double a, double b) { ... }`
* Method Overriding: `@Override public void makeSound() { System.out.println("Meow"); }`
**6. Abstraction**:
* Using abstract classes and interfaces to define methods that must be implemented, without providing concrete implementations.
* Example:
* Abstract Class: `public abstract class Shape { abstract void draw(); }`
* Interface: `public interface Animal { void eat(); }`
**7. Interface**:
* Defines methods that a class must implement, supporting multiple inheritance.
* Example: `public interface Drivable { void drive(); }`
**8. Method**:
* Defines the behavior of a class, functions contained within the class.
* Example: `public void displayInfo() { System.out.println("Info"); }`
**9. Method Overloading**:
* Multiple methods with the same name can exist in the same class, but with different parameters.
* Example: public class MathUtils { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; }}
In this section, we will focus on the concepts of objects and classes.
* **Object**: An object is an instance of a class (**an object is not about finding a girlfriend**), possessing state and behavior. For example, a dog is an object; its state includes: color, name, breed; its behaviors include: wagging tail, barking, eating, etc.
* **Class**: A class is a template that describes the behavior and state of a category of objects.
In the diagram below, **boy** and **girl** are **classes**, while specific individuals are **objects** of that class:
!(#)
In the diagram below, **Car** is a **class**, while specific cars are **objects** of that **Car** class. The objects contain the car's color, brand, name, etc.
!(#)
* * *
## Objects in Java
Now let's delve deeper into what an object is. Look at the real world around you; you'll find many objects: cars, dogs, people, etc. All these objects have their own state and behavior.
Take a dog as an example. Its state includes: name, breed, color. Its behaviors include: barking, wagging its tail, and running.
Comparing real-world objects and software objects, they are very similar.
Software objects also have state and behavior. The state of a software object is its attributes, and its behavior is represented by methods.
In software development, methods manipulate changes to an object's internal state, and the interaction between objects is also accomplished through methods.
## Classes in Java
A class can be seen as a template for creating Java objects.
!(#)
By creating a simple class based on the diagram above, let's understand the definition of a class in Java:
public class Dog{String breed; int size; String colour; int age; void eat(){}void run(){}void sleep(){}void name(){}}
A class can contain the following types of variables:
* **Local Variables**: Variables defined within methods, constructors, or statement blocks are called local variables. Variable declaration and initialization occur within the method, and the variable is automatically destroyed after the method ends.
* **Member Variables**: Member variables are defined within a class, outside the method body. These variables are instantiated when an object is created. Member variables can be accessed by methods, constructors, and specific statement blocks within the class.
* **Class Variables**: Class variables are also declared within a class, outside the method body, but must be declared as `static` type.
A class can have multiple methods. In the example above: `eat()`, `run()`, `sleep()`, and `name()` are all methods of the `Dog` class.
* * *
## Constructors
Every class has a constructor. If you do not explicitly define a constructor for a class, the Java compiler will provide a default constructor for that class.
When creating an object, at least one constructor is called. The constructor's name must be the same as the class name, and a class can have multiple constructors.
Here is an example of a constructor:
public class Puppy{public Puppy(){}public Puppy(String name){// This constructor has only one parameter: name}}
* * *
## Creating Objects
Objects are created based on classes. In Java, the keyword `new` is used to create a new object. Creating an object requires the following three steps:
* **Declaration**: Declare an object, including the object name and object type.
* **Instantiation**: Use the keyword `new` to create an object.
* **Initialization**: When creating an object with `new`, the constructor is called to initialize the object.
Here is an example of creating an object:
public class Puppy{public Puppy(String name){// This constructor has only one parameter: name System.out.println("Puppy's name is : " + name); }public static void main(String[]args){// The following statement will create a Puppy object Puppy myPuppy = new Puppy("tommy"); }}
Compiling and running the program above will print the following result:
Puppy's name is : tommy
* * *
## Accessing Instance Variables and Methods
Member variables and member methods are accessed through the created object, as shown below:
/* Instantiate an object */Object referenceVariable = new Constructor(); /* Access a variable in the class */referenceVariable.variableName; /* Access a method in the class */referenceVariable.methodName();
Declaring a variable of type `Object` only allows access to methods and properties within the `Object` class at compile time. However, at runtime, you can cast it to a specific type to access the methods and properties of that specific type.
* * *
## Example
The following example demonstrates how to access instance variables and call member methods:
## Puppy.java File Code:
public class Puppy{private int age; private String name; // Constructor public Puppy(String name){this.name = name; System.out.println("Puppy's name is : " + name); }// Set the value of age public void setAge(int age){this.age = age; }// Get the value of age public int getAge(){return age; }// Get the value of name public String getName(){return name; }// Main method public static void main(String[]args){// Create an object Puppy myPuppy = new Puppy("Tommy"); // Set age via method myPuppy.setAge(2); // Call another method to get age int age = myPuppy.getAge(); System.out.println("Puppy's age is : " + age); // You can also access member variables directly (via getter method)System.out.println("Variable value : " + myPuppy.getAge()); }}
Compiling and running the program above produces the following result:
Puppy's name is : tommy Puppy's age is : 2Variable value : 2
* * *
## Source File Declaration Rules
In the final part of this section, we will learn about the declaration rules for source files. When defining multiple classes in a single source file, along with `import` statements and `package` statements, pay special attention to these rules:
* Only one `public` class can exist in a source file.
* A source file can have multiple non-`public` classes.
* The source file name should match the name of the `public` class. For example: if the `public` class in the source file is named `Employee`, then the source file should be named `Employee.java`.
* If a class is defined within a package, the `package` statement should be the first line in the source file.
* If the source file contains `import` statements, they should be placed between the `package` statement and the class definition. If there is no `package` statement, the `import` statements should be at the very beginning of the source file.
* `import` statements and `package` statements apply to all classes defined in the source file. Different package declarations cannot be given to different classes within the same source file.
Classes have several access levels, and classes are also of different types: abstract classes and final classes, etc. These will be introduced in the Access Control chapter.
In addition to the types mentioned above, Java has some special classes, such as: (#), (#).
* * *
## Java Packages
Packages are mainly used to categorize classes and interfaces. When developing Java programs, you may write hundreds or thousands of classes, so it is necessary to categorize classes and interfaces.
## import Statements
In Java, if you provide a fully qualified name, including the package name and class name, the Java compiler can easily locate the source code or class. The `import` statement is used to provide a reasonable path to make
YouTip