It's not clear how to object-oriented yet?

Posted by ruach on Sat, 13 Jun 2020 20:23:52 +0200

This paper mainly introduces the basic idea and three characteristics of object-oriented.

The article was first published under the public slogan Pedestrian View.

1. Introducing Examples

Create a Dog puppy

/**
 * Puppies
 */
public class Dog {
    String name;
    Integer age;
    Integer legs;

    public void say(String name) {
        System.out.println("I am"+ name +",Wangwang");
    }
    
    public void watchDoor() {
       System.out.println("Chase away strangers");
    }
}

Puppies can have such attributes as name, age, number of legs, and the behavior of "barking", which are common to puppies.

From the code above, you can see that a class defines the abstract characteristics of a thing.The definition of a class includes the form of the data and the manipulation of the data.

When we play with a puppy, we are not playing with a "kind of dog", but with a "specific dog", such as a wheezing dog.

So only Dog can't play with a dog. We need a specific dog. Where does this specific dog come from?In real life, we may have to spend money on a specific dog in a pet store.In the programming world, we also need to spend "money" to "buy", but here "money" refers to "memory", "buy" refers to "new", "specific dog" refers to "object" instantiated.

/**
 * Instantiate a puppy and play with it
 */
public class Play {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "Wheezing dog";
        dog.age = 2;
        dog.legs = 4;
        dog.say(dog.name);
        dog.watchDoor();
    }
}

//Running, Output
    //I am a wheezing dog, woody
    //Chase away strangers

Now we spend money (memory) on a two-year-old, four-legged puppy named the Whooping Dog. It has specific attributes and behavior and is a "living dog".

As you can see from the code above:

  • Objects are instances of classes.
  • The system allocates memory space to objects, not to classes.It's understandable that classes are abstract, and it's impossible for the system to allocate space to abstract things, while objects are concrete.

2. Three Object-Oriented Features

With the examples above, the concepts of classes and objects and the relationship between them are briefly introduced.Here we introduce the three main features of object-oriented.

1. Packaging

Now let's analyze the problem with the puppy example above.

  • For a Dog class, its properties and methods are all exposed, i.e., visible from outside the class.In this way, the puppy has no privacy right.
  • When we instantiate a puppy, we assign its attributes directly, which means we can modify the puppy's attributes outside of the class.This means that when we buy a puppy, we can change its name, age or even the number of legs (horrible).

In the example above, the data in our class can be accessed and modified at will, which is a big problem.

Once we find the problem, we need to solve it, and the solution is to encapsulate it.

The following encapsulates the Dog class:

/**
 * Encapsulate puppies
 */
public class Dog {
    private String name;
    private Integer age;
    private Integer legs;

    public void say(String name) {
        System.out.println("I am"+ name +",Wangwang");
    }

    public void watchDoor() {
        System.out.println("Chase away strangers");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getLegs() {
        return legs;
    }
    
    public void setLegs(Integer legs) {
        this.legs = legs;
    }
}

We set the properties of puppies to private, hide the data, and only this class can access it.

/**
 * Instantiate a puppy and play with it
 */
public class Play {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.setName("Wheezing dog");;
        dog.setAge(2);
        dog.setLegs(4);
        dog.say(dog.getName());
        dog.watchDoor();
    }
}

External classes can modify and access properties only through setter and getter methods.These setter and getter methods are voluntarily exposed by the Dog class and are the entries for external classes to access the properties of the class. If the Dog class does not want some of its properties to be accessed and modified by external classes, then close these entries.

Encapsulation encapsulates data and methods of manipulating data, hides data, avoids external interference and misuse, and allows external code not to access internal object data directly, but only through allowed methods.This avoids unnecessary relationships between external code and objects, and we don't need to modify external code when refactoring class internal code (as long as Entry is invoked in the same way).

In the above, we instantiate a specific puppy "wheezing dog" based on the Dog class, while encapsulation makes the individual more independent, autonomous and safe.

2. Inheritance

Before we went to the pet store and bought a dog called the wheezing dog. There are many other kinds of pets in the pet store, cats, rabbits, birds, fish...

Here we write out their classes:

/**
 * Cats
 */
public class Cat {
    private String name;
    private Integer age;
    private Integer legs;

    public void say(String name) {
        System.out.println("My name is"+name+",cat");
    }

    public void catchMouse() {
        System.out.println("Catch a mouse");
    }

    setters and getters
}
/**
 * Rabbits
 */
public class Rabbit {
    private String name;
    private Integer age;
    private Integer legs;
    private String home;


    public void say(String name) {
        System.out.println("My name is"+name+",Google");
    }

    public void makeMedicine() {
        System.out.println("pound medicine in a mortar");
    }

    setters and getters
}

After writing about cats and rabbits, we found that there were many duplicates of attributes and methods, but there were many pets in the pet store...

Once we find the problem, we need to solve it, and the solution is to inherit.

Inheritance involves both parent and child classes, which are further abstractions of the subclasses, which are more specific than the parent.Subclasses inherit the properties and behavior of the parent class, meaning that the same code only needs to be written once.

/**
 * Animals, Parents
 */
public class Animal {
    private String name;
    private Integer age;
    private Integer legs;

    public void say(String name) {
        System.out.println("I am"+name+"Make a sound");
    }

    setters and getters
}
/**
 * Dogs, subclass.Inherit Animal Parent
 */
public class Dog extends Animal {
    
    public void say(String name) {
        System.out.println("I am"+ name +",Wangwang");
    }

    public void watchDoor() {
        System.out.println("Chase away strangers");
    }
}
/**
 * Cats, subclasses.Inherit Animal Parent
 */
public class Cat extends Animal {

    public void say(String name) {
        System.out.println("I am"+name+",cat");
    }

    public void catchMouse() {
        System.out.println("Catch a mouse");
    }
}
/**
 * Rabbits, subclass.Inherit Animal Parent
 */
public class Rabbit extends Animal{
    private String home;

    public void say(String name) {
        System.out.println("I am"+name+",Google");
    }

    public void makeMedicine() {
        System.out.println("pound medicine in a mortar");
    }

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }
}

We'll pull out the same code and place it in the more abstract class Animal, called the parent class.More specific classes with Animal member variables and methods such as Dog, Cat, Rabbit don't have to repeat those codes anymore, just inherit the Animal class using the extend ed keyword.

  • Subclasses can have their own member variables and methods, that is, extended parent classes.Examples include the Rabbit class home member variable and the makeMedicine() method.
  • If a subclass feels that the method inherited from its parent is inappropriate, it can override the implementation of the parent's method, noting that return values and parameters cannot be changed.For example, the void say(String name) method.
public class Play {
    public static void main(String[] args) {
        Rabbit rabbit = new Rabbit();
        rabbit.setName("Jade Hare");
        rabbit.setAge(1000);
        rabbit.setLegs(4);
        rabbit.setHome("Guanghan Palace");
        rabbit.say(rabbit.getName());
        rabbit.makeMedicine();
    }
}

//Running, Output
    //My name is Jade Rabbit and I cook
    //pound medicine in a mortar

As you can see from the examples above, inheritance can be used to:

  • Enhance the reusability of your code so you don't have to write as many duplicates anymore.
  • To make the code maintainable, when we need to modify a common method, we don't need to modify each class, just the method of the parent class.

3. Polymorphism

Let's look at the code below to visualize what polymorphism is.

public static void main(String[] args) {
    Animal dog = new Dog();
    dog.setName("Wheezing dog");
    dog.say(dog.getName());

    Animal cat = new Cat();
    cat.setName("Garfield");
    cat.say(cat.getName());

    Animal rabbit = new Rabbit();
    rabbit.setName("Jade Hare");
    rabbit.say(rabbit.getName());
}

//Running, Output
    //I am a wheezing dog, woody
    //I'm Garfield Cat, meow
    //I am a Jade Rabbit, croaking
  1. Dog, Cat, and Rabbit all inherit the Animal parent.
  2. Dog, Cat, and Rabbit all override Animal's say(String name) method.
  3. When creating instance objects, we use parent references to objects pointing to subclasses.

A few things to note when using polymorphisms: Animal dog = new Dog()

  • In polymorphism, subclass objects can only call methods defined in the parent class, not methods unique to the subclass.

    For example, a dog cannot call the watchDoor() method.

  • In polymorphism, a subclass can call all methods of the parent class.
  • In polymorphism, if a subclass overrides the method of the parent class, then when the subclass calls the method, it calls the method overridden by the subclass.

In the code above, dog, cat, rabbit objects all run the say method, but the output is different.

It can be seen from this that the same behavior of different objects has different manifestations, which is called polymorphism.

In this real case, we can understand that when you go to a pet store to buy a pet Animal, they all shout.If you buy a dog, you will call Wangwang; if you buy a cat, you will call Miaomiao; if you buy a rabbit, you will call Grunt.

3. Summary

Object-oriented thinking enables us to program closer to the real world. Class is the abstraction of the real world, while object is a specific thing.Encapsulation makes a specific thing more independent, inheritance makes these similar things related, and polymorphism makes things behave more flexibly and diverse.

Object-oriented programming improves the reusability, flexibility and extensibility of software.

If there are any errors, please correct them.

Topics: Java Programming Google