Details of encapsulation inheritance and polymorphism in Java

  • 2020-05-30 20:19:00
  • OfStack

encapsulation

In the article on how to understand object orientation, it is said that encapsulation means "the functionality is all there for you, you don't have to understand how it was written, just use it." . But one thing you have to be clear about is that this is relative to the consumer, and as developers, encapsulation is up to us.

So how do we, as developers, encapsulate this? In fact you should, in turn, asked, they should be how to use, 1 want to will be much simpler, as users, natural was as simple as possible, that is to say, 1 some complicated things, we should not let the user to operate, that is to say we should have the complex, and unnecessary parameters to sealed it, don't let the user to operate.

Why not let the user do it?

Because often the user is not very professional, if exposed to too much to them, the interface is very likely to be 1 some strange questions, like 1 will not be boiled fish, if let him do it must be bad, how to do it, to buy him a bag of boiled fish sauce, it is good to let him directly into the pot, thus reduce the unnecessary trouble. The same is true of our encapsulation program, which blocks complex code from the operator to avoid errors.

Here's an example:


class Average{
 private int[] fractions = new int[3]; // score 
 private int average = 0; // average 
 public void setFraction(int[] fraction){
  fractions = fraction;
 }
 public double getAverage(){
  for(int cell:fractions){
   average += cell;
  }
  return (double) (average / fractions.length);
 }
}
class app{
 public static void main(String[] args){
  int[] a = {50,40,50};
  Average average = new Average();
  average.setFraction(a); // Set the score 
  double n = average.getAverage(); // Get an average score 
  System.out.println(average.average); // An error 
  System.out.println(n); //46.0
 }
}

Tip: Java sets private variables through private, and public sets variables to public.

Here, the reason why we set the score and average score to private variables is to prevent the user from misoperating, and the user does not need to know that there is such a variable, just need to let the user know how to set the score and get the average score.

Of course, this is only a very basic encapsulation, if you want to encapsulate a good program, you have to pay more attention.

inheritance

Take cat and dog for example, they are both animals, and they have some things in common, such as name, age, voice, eating and so on. This is what it looks like to write this as code.


class Animal{
 private String name;
 private int age;

 public void setName(String name){
  this.name = name;
 }
 public void setAge(int age){
  this.age = age;
 }
 public String getName(){
  return this.name;
 }
 public int getAge(){
  return this.age;
 }
}
class Cat extends Animal{
 public void voice(){
  System.out.println(super.getName() + "  meow ");
 }
 public void eat(){
  System.out.println(super.getName() + " fish");
 }
}
class Dog extends Animal{
 public void voice(){
  System.out.println(super.getName() + "  wang ");
 }
 public void eat(){
  System.out.println(super.getName() + " Bone");
 }
}
class app{
 public static void main(String[] args){
  Cat cat = new Cat();
  cat.setName(" The cat king "); //Cat Itself has no setName Method, but its base class has, so java The parser will arrive Cat The base class gets there 
  cat.voice();
  Dog dog = new Dog();
  dog.setName(" A big black ");
  dog.setAge(13);
  dog.voice();
  System.out.println(dog.getName() + dog.getAge());
 }
}

------Output------
 The cat king   meow 
 A big black   wang 
 A big black 13

Note: Java USES the extends keyword to implement inheritance. Variables and methods defined by private in the parent class will not be inherited, which means you cannot directly manipulate variables and methods defined by private in the child class.

In the code above, we can see that Cat and Dog did not define setName, setAge, getName, getAge method, but we can still use in Cat and Dog class, it is because we inherited by extends keywords Animal class, therefore in Animal defined variables and methods, we can directly use in subclasses, except private defined variables and methods.

On the other hand, names and ages are basic information about cats and dogs as well as their common characteristics.

Overrides a superclass method or variable

Overrides the parent method because you treat the cat as a base class and inherit the dog from the cat class. It may seem funny, but if you go through your code, it happens a lot. Of course, if you don't need inheritance, that's another story. So if that happens, how do we override the base class? Quite simply, define 1 method in the subclass and 1 method in the parent class, as follows:


class Animal{
 private String name;
 private int age;

 public void setName(String name){
  this.name = name;
 }
 public void setAge(int age){
  this.age = age;
 }
 public String getName(){
  return this.name;
 }
 public int getAge(){
  return this.age;
 }
}
class Dog extends Animal{
 public String getName(){
  return super.getName() + "2";
 }
 public void voice(){
  System.out.println(super.getName() + "  wang ");
 }
 public void eat(){
  System.out.println(super.getName() + " Bone");
 }
}
class app{
 public static void main(String[] args){
  Dog dog = new Dog();
  dog.setName(" A big black ");
  System.out.println(dog.getName()); // Execution is Dog In the getName methods 
 }
}

Tip: you can call the parent class's methods and variables directly from a subclass via super, and the current class via this.

I don't think it's a good idea to call this an override, because if it's not an override per se, it's just Java's rules for finding variables and methods. Java will look at 1 first, if there is any variable or method on him or her, if there is no one in the parent class, then he or she will look for it in the parent class, if there is no one in the parent class, then he or she will look for it at the next level. If there is no one in the parent class, then he or she will report an error.

When overwriting a parent class, it is important to note that 1. When overwriting, the return value type of the method must be the same as 1 defined in the parent class. If it is a numeric type, as long as the overwriting type is not greater than that defined in the parent class, then it is ok. For example, the following will give you an error


class Animal{
 private String name;
 public void setName(String name){
  this.name = name;
 }
 public String getName(){
  return this.name;
 }
}
class Dog extends Animal{
 public int getName(){ // And the parent class getName Returns a different value and reports an error 
  return 123;
 }
}
class app{
 public static void main(String[] args){
  Dog dog = new Dog();
  System.out.println(dog.getName());
 }
}

Also note that if you overwrite something that does not correspond to a parameter in the parent class, something unexpected will happen, such as this


class Animal{
 private String name;

 public void setName(String name){
  this.name = name;
 }
 public String getName(String hello){
  return this.name + hello;
 }
}
class Dog extends Animal{
 public String getName(){
  return "123";
 }
}
class app{
 public static void main(String[] args){
  Dog dog = new Dog();
  dog.setName(" A big black ");
  System.out.println(dog.getName("hello"));
 }
}

------Output------
 A big black hello

You can see that when we communicate the parameters to getName, we are executing the Animal method instead of the getName method in Dog, which means that if the parameter is not 1, the last method to be executed may not be the overwritten method. In addition, you cannot change the method or variable exposed by the parent class to private (such as changing public to private), otherwise you will also report an error. I estimate that Java has a set of overwriting rules, and if the conditions are not met, it will not be overwritten.

In summary, overwriting a parent method or variable is more lenient than the other way around.

polymorphism

Let's do a couple of examples before we get to the theory


class Animal{
 public int age = 5;

 public int getAge(){
  return age;
 } 
}
class Dog extends Animal{
 public int age = 8;

 public int getAge(){
  return age + 2;
 }
}
class app{
 public static void main(String[] args){
  Animal dog = new Dog();
  System.out.println(dog.age);
 }
}

------Output------
5

Animal dog = new Dog(); You can see that they are not of the same type, but they work because the Dog class is a subclass of Animal, and the parent class includes subclasses. When we say animal, is a dog one of the animals? That's for sure, and that's why it works.

But need to pay attention to 1, the objects created by this way, when for instance variables, and access to the instance variable in the parent class, if it is a method, is to look at whether there is in the subclass and of the same name in the parent class, use the method in a subclass if there is, but if have a method in a subclass, and not in the parent class, then it will be an error. The following code will report an error


class Animal{
 public int age = 5;
 public int getAge(){
  return age;
 }
}
class Dog extends Animal{
 public int age = 8;

 public int getAge(){
  return age + 2;
 }
 public setAge(int a){
  this.age = a;
 }
}
class app{
 public static void main(String[] args){
  Animal dog = new Dog();
  System.out.println(dog.setAge(5));
 }
}

Because there is no setAge method in the parent class, an error is reported.

In other words, by writing in this way, can only achieve the effect of the overwrite method, no other function.

What's called polymorphic here, in a program you can think of it as 1 method, it can have different effects, so how do you achieve different effects? This is done in java by switching the type (not always correct).

What's the use of polymorphism?

Let's do a couple more examples


class Animal{
 public int age = 5;

 public int getAge(){
  return age;
 }
}
class Dog extends Animal{
 public int getAge(){
  return age + 2;
 }
}
class Cat extends Animal{
 public int getAge(){
  return age + 3;
 }
}
class app{
 public static void main(String[] args){
  Animal dog = new Dog();
  Animal cat = new Cat();

  System.out.println(dog.getAge());
  System.out.println(cat.getAge());
 }
}

------Output------
7
8

As you can see, it performs different methods depending on itself. On the other hand, this doesn't really mean anything, because we can create it as it should, and it can be just as good, but it does have its USES, like this code


class Animal{
 public int age = 5;

 public int getAge(){
  return age;
 }
}
class Dog extends Animal{
 public int getAge(){
  return age + 2;
 }
}
class Cat extends Animal{
 public int getAge(){
  return age + 3;
 }
}
class app{
 public static void main(String[] args){
  Animal[] animals = new Animal[2];
  animals[0] = new Dog();
  animals[1] = new Cat();

  System.out.println(animals[0].getAge());
  System.out.println(animals[1].getAge());
 }
}

------Output------
7
8

This code is similar to the one above, but this one USES an array, which is a good place to use polymorphism, otherwise there is no other way to do it. Polymorphism in this case is not just about one method having different effects, but also about the variety of types.


Related articles: