banner
云上月枫下叶

云枫のblog

写代码是因为爱,写到世界充满爱!
email
github
twitter
tg_channel

Object-oriented thinking in Java

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#

Image

Encapsulation#

Image

Inheritance#

Image

Image

Polymorphism#

Image

Classes and Objects#

Image

Image

Encapsulation of Classes#

Constructors#

Static Methods#

The following is an incorrect example:

Image

Image

Image

The "this" Keyword#

The "static" Keyword#

Inheritance with "extends"#

Overriding a Parent Class#

The "super" Keyword#

Image

Image

The "final" Keyword#

Image

Image

Image

Abstract Classes#

Abstract classes (can contain both abstract and regular methods) and interfaces (can only contain abstract methods)

Image

Interfaces#

Image

Image

Image

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

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.