We will summarize the encapsulation and inheritance of the three major object-oriented functions.
Encapsulation is a function that restricts reading and writing to fields and method calls. Encapsulation makes it possible, for example, to limit the caller, or to read the contents of a field but not to write it.
Encapsulation by setting access control Use access modifiers to set access control The access modifiers are as follows
name th> | Permission range th> |
---|---|
private | Only my own class td> |
protected | The same package as you or a class that inherits you td> |
public | All classes td> |
Private in the field The method is public
Prepare getters and setters to access the fields
Validate arguments in setter
Used to reuse similar classes
By adding methods and fields to the parent element, it is not necessary to set them individually for the child elements. The behavior can be changed individually by overriding.
Example
class Car {
private double gas;
}
class superCar extends Car {
private int speed;
}
This way, the supercar can have a speed field in addition to the Car gas field.
Force the class that defines the method and implements the interface to define the defined method Multiple inheritance is allowed
interface Human {
public void run();
}
class taro implements Human {
//taro raises an error because no run method is defined
}
Recommended Posts