About Java object generation (?)

Asked 2 years ago, Updated 2 years ago, 55 views

When you create an object in Java, There are times when you use Box-Box, such as Box<String> box = new Box<>(); There are times when I use Set-HashSet, such as Set<String>set1 = new HashSet<>();. 1. I think using Set-HashSet for inheritance 2. HashSet already inherits Set, so isn't it okay to use HashSet<String>set1 = new HashSet<>();? 3. Why should I use Set-HashSet?

1, 2, 3. I want to solve the question. Please explain if there are any other mistakes.

java object

2022-09-21 15:56

1 Answers

This is a question that requires an understanding of object orientation.

For example, all animals eat and sleep. However, the method differs only from animal to animal, that is, the act of eating and sleeping.

Animal tiger = new Tiger();
Animal lion = new Lion();

// an abstraction of behavior
public void processEat(Animal animal){
    animal.eat();
}

public void processSleep(Animal animal){
    animal.sleep();
}

processEat(tiger);
processSleep(tiger);

processEat(lion);
processSleep(lion);
Tiger tiger = new Tiger();

// Generating behavior for each animal
public void processEat(Tiger tiger){
    tiger.eat();
}

public void processSleep(Tiger tiger){
    tiger.sleep();
}

Lion lion = new Lion();
public void processEat(Lion lion ){
    lion.eat();
}

public void processSleep(Lion lion ){
    lion.sleep();
}
...
...

The second question is, what if there are a thousand animals that have to eat and eat? You need to make a thousand processEat, processSleep.

But in the first example, because it's abstracted, that's because every animal implements an animal, it's possible to do it in one method.

If...If the processEat method needs to be modified...For the second example method, you need to modify a thousand methods.

Please consider the benefits of object orientation.


2022-09-21 15:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.