Fundamentals of Java programming IV: Object Oriented Programming

Posted by Dillenger on Mon, 07 Mar 2022 10:01:49 +0100

Chapter IV object oriented programming

1 object oriented and process oriented

  • Both of them are a kind of thought, and object-oriented is relative to process oriented. Process oriented emphasizes the functional behavior, taking the function as the smallest object and considering how to do it. Object oriented, encapsulating functions into objects, emphasizing objects with functions. Take the class / object as the minimum unit and consider who will do it.

  • Three characteristics of object-oriented

    Encapsulation

    Inheritance

    Polymorphism

2 java basic elements: classes and objects

Classes: attribute methods

3 creation and use of objects

class Person{
    String name;
    int age;
    boolean isMale;
    public void eat(){
        System.out.println("People can eat");
    }
    public void sleep(){
        System.out.println("People can sleep");
    }
}
Person p = new Person();
p.name = "Tom";
p.isMale = true;
p.age = 18;
p.eat();p.sleep();

One of the members of class 4: properties

Attribute vs local variable

  1. Same point
  • The format of defining variables is the same. Data type variable name = variable value
  • Declaration before use
  • Variables have corresponding scopes
  1. difference
  • The positions declared in the class are different

    Attribute: directly defined in {} of class

    Local variables: variables declared within methods, method parameters, code blocks, constructor parameters, and constructors

  • Differences about permission modifiers

    Attribute: the attribute can be declared again, indicating permission and using permission modifier.

    Local variable: permission modifier cannot be used.

    Common permission modifiers: private, public, default, protected, final

  • Default initialization value

    Attribute: the attribute of a class has a default initialization value according to its type.

    typeDefault value
    Integer byte, short, int, long0
    Floating point double, float0.0
    Character char0
    Booleanfalse
    Reference data type, class, array, interfacenull

    Local variable: no default value.

    Special: when the formal parameter is called, it can be assigned

  • The location of loading in memory is different

    Properties: loading into heap space

    Local variables: loading into stack space

Class 5 member 2: Methods

  1. give an example
  • Classification according to whether there are formal parameters

    No return valueThere is a return value
    Invisible parametervoid method(){}Return value type method() {}
    Formal parameterVoid method (formal parameter list) {}Return value type method (formal parameter list) {}
  1. Declaration of method:

    Permission modifier return value type method name (formal parameter list){

    Method body

    }

  2. Method name: an identifier. See the meaning of the name

  3. Use of the return keyword

  • Use in method

  • effect:

    End method

    For methods with return values, use return to return the desired data.

    Example 1:

public class CircleTest{
    public static void main(String[] args){
        Circle c1 = new Circle();
        c1.radius = 2;
        System.out.println("The area of the circle is:" + c1.findArea());
        System.out.println("The area of the rectangle is:" + method(12,8));
        }
    public static void method(int m,int n){
        return m * n;
    }
}
class Circle{
    double radius;
    public double findArea(){
        return Math.PI * radius * radius;
    }
}

Example 2:

public class StudentTest{
   public static void main(String[] args){
       Student[] students = new Student[20];
       for(int i = 0;i < students.length;i++){
           students[i] = new Student();
            students[i].number = (i + 1);
            students[i].state = (int)(Math.random() * 6 + 1);
           students[i].score = (int)(Math.random() * (100 - 0 + 1) + 1);
       }
   } 
}
class Student{
    int number; //Student number
    int state;	//grade
    int score;  //score
}

6 extension I

6.1 use of anonymous objects

public class InstanceTest{
    public static void main(String[] args){
        Phone p = new Phone();
        p.sendEmail();
        p.playGame();
        
        //anonymous
        new Phone().sendEmail();
         new Phone().playGame();
        
    }
}
class Phone{
    double price;
    public void playGame(){
        System.out.println("play a game");
    }
    public void sendEmail(){
        System.out.println("send emails");
    }
}

6.2 overloading of methods

  1. definition

    In the same class, more than one method with the same name is allowed, as long as their parameter number or parameter type are different

public class OverLoadTest{
    public static void main(String[] args){
   	        
       OverLoadTest olt = new OverLoadTest();
       System.out.println(olt.getSum(1.2,2.0));
        //If you don't want to declare an object, directly output getSum(); You need to declare the method as static
        //Static methods can be called directly without object instances
    }
    //The following methods constitute refactoring
    public int getSum(int i,int j){
        return i + j;
    }
    public double getSum(double i,double j){
        return i + j;
    }
}

6.3 methods of variable number formal parameters

  1. Variable number parameter format array type... Variable name
public void show(String ... strs){
    //TODO
}
//When calling variable number formal parameters, any number of parameters will be passed in
  1. Variable number shape participating array types cannot exist at the same time
public void show(String ... strs){}
public void show(String[] strs){}
//JDk5.0 used array before, so it cannot exist at the same time
  1. Variable number formal parameters must be declared last in the formal parameters of a method, and only one deformable parameter can be declared
public void show(int i,String ... strs){}
  1. Class for value conversion of reference type
class Data{
	int m;
	int n;
}
main(){
	Data data = new Data();
	data.m = 10;
	data.n = 20;
	swap(data.m,data.n);
}
swap(){
	int temp = data.m;
	data.m = data.n;
	data.n = temp;
}

7 extension II

7.1 OOP feature 1: Encapsulation

  • Privatization of attributes and public ownership of methods
class Animal{
    //Privatization attribute, public method
    private String name;
    private int age;
    private int legs;
    
    //Automatically generate Getter and Setter methods
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    //When a property has no matching getter and setter methods, the property name is directly used as the method name
    public int legs(){//In fact, the full name of the method is getLegs()
        return legs;
    }
    //JavaBean
}
  • Permission modifier
Modifier Class interiorSame packageSubclasses of different packagesSame project
private
default
protected
public

The third member of class 7.2: constructor

  1. effect

Create object

  1. explain
  • If the constructor of the class is not explicitly defined, an empty parameter constructor is provided by default (the permission follows the permission of the class)
  • Define the format of the constructor: permission modifier class name (formal parameter list) {}
  1. JavaBean
  • Class is public
  • There is a public parameterless constructor
  • There are properties and corresponding get and set methods

8 use of keywords

8.1 use of this keyword

  1. this can be used to decorate: properties, methods, constructors
  2. this modifier attribute and method:
  • this is understood as: current object
  1. this call constructor
  • You can call other constructors with this() in the constructor. The specific call depends on the formal parameter
  • Constructor cannot call itself through this (formal parameter list)
  • Regulation: this (formal parameter list) must be placed in the first line of this constructor, and only one can be called

8.2 use of package keyword

  1. In order to better realize the management of classes in the project
  2. Use package to declare the package to which the class or interface belongs, which is declared on the first line
  3. You need to know the meaning of the name. Generally, it is the reverse writing of the domain name
  4. Each "." Represents the first level file directory

Topics: Java