Object-oriented Programming#
Object-oriented programming is a programming paradigm that models complex real-world scenarios as a series of objects, expressing the relationships between objects to closely resemble the way we think in the real world. It is a declarative programming approach that translates user requirements into actual operations. The object-oriented approach maps entities and relationships from the real world into objects and expresses the relationships between these objects. When a program interacts with these objects, it aligns more closely with human thinking patterns, making the program easier to understand and maintain.
Features#
Encapsulation#
Inheritance#
Polymorphism#
Classes and Objects#
Encapsulation of Classes#
Constructors#
Static Methods#
The following is an incorrect example:
The "this" Keyword#
The "static" Keyword#
Inheritance with "extends"#
Overriding a Parent Class#
The "super" Keyword#
The "final" Keyword#
Abstract Classes#
Abstract classes (can contain both abstract and regular methods) and interfaces (can only contain abstract methods)
Interfaces#
interface Animal {
public void animalSound(); // Interface method (no need to write the abstract keyword, interface methods are abstract by default)
public void sleep(); // Another interface method (abstract)
}
class Pig implements Animal {
public void animalSound() {
// Implementing the interface method
System.out.println("The pig says: wee wee");
}
public void sleep() {
// Implementing the interface method
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
In this example, we define an Animal
interface and then implement it in the Pig
class. The Pig
class needs to implement all the methods of the interface, otherwise it will throw an error. Finally, in the Main
class, we call the animalSound()
and sleep()
methods of this Pig
object. This approach allows us to use the same interface in different classes, increasing code reusability and flexibility.
Polymorphism#
ParentClass object1 = new ChildClass();
Object type conversion
Object class: the parent class of all classes
Exceptions#
try...catch and finally
Throws keyword