A comprehensive summary of Java object oriented and encapsulation

  • 2021-12-04 19:00:25
  • OfStack

Personal understanding of object-oriented and encapsulation

Classes and Objects

Class: A description of things (abstraction of things with common attributes and behaviors), such as mobile phones, attributes: brand price, behavior: playing games, brushing vx;;

Object: Objective existence (embodied in java is that in mian method, an object is defined by class, and then the object is used to call the method or call the member variable)

Two-person relationship: class is attribute behavior abstraction, and object is entity.

Object memory diagram understanding: Heap memory opens up space, member variables appear and produce default initialization values, and object address values are recorded to facilitate calling member variables through object names.

Differences between member variables and local variables: different positions in classes, different positions in memory, different life cycles and different initialization values (member variables (with default initialization values) and local variables (without default initialization values, they must be defined and assigned before they can be used).

Encapsulation

private keyword: Members modified by private can only be accessed in this class. For member variables modified by private, if they need to be used by other classes, provide corresponding operations (get, set methods)

this keyword: this modified variables are used to refer to member variables, and their main function is to distinguish local variables from member variables with duplicate names.

Encapsulation understanding: Some information of the class is hidden inside the class, and external programs are not allowed to access it directly. Instead, the operation and access to the hidden information are realized through the methods provided by the class (private modification and get, set methods)

The advantage and function of encapsulation: Encapsulate the code with methods, improve the reusability of the code, control the operation of member variables through methods, improve the security of the code.

Problem summary

Bank account

package test3;

public class bank {
    public static void main(String[] args) {
        // Testing the class Bank Create bank account class objects and user class objects in, 
        //  And set the information, and display the information 
        Customer customer = new Customer(" Li Hua ","123456789","987456321"," Xinhua community ");
        Account  account = new Account(1111115646,1000000,customer);
        customer.say();
        account.withdraw( 10000 );
        account.save( 9999999 );
        System.out.println(customer.say());
        System.out.println(account.getinfo());
        if (account.withdraw( 10000 )==true){
            System.out.println(" Successful withdrawal of money ");
            System.out.println(" The balance is still "+account.getBalance());
        }else{
            System.out.println(" Withdrawal failure ");
        }
        if (account.save( 444444 )==true){
            System.out.println(" Deposit success ");
            System.out.println(" The balance is still "+account.getBalance());
        }else{
            System.out.println(" Deposit failure ");
        }
    }
}
package test3;
/*2. Define bank account classes Account Attributes: Card number cid , balance balance The user to which it belongs Customer  
 Bank account category Account There are ways: ( 1 ) getInfo() , return String Type, which returns the details of the card 
 ( 2 ) Method of withdrawing money withdraw() The parameters are designed by ourselves, and if the money is withdrawn successfully, it will be returned true Failure returns false
 ( 3 ) Methods of saving money save() The parameters are designed by ourselves, and if the deposit is successful, it will return true Failure returns false  
  Among them Customer Class has attributes such as name, ID number, contact phone number, and home address     Customer Class has methods say() , 
  Return String Type, returning his personal information. ​ Testing the class Bank Create bank account class objects and user class objects in, 
  And set the information, and display the information */
public class Account {
    private int cid ;
    private int balance;
    private Customer customer;

    public Account(Customer customer) {
        this.customer = customer;
    }

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }
    public Account(String s, int balance, Customer customer){

    }
    public Account(int cid,int balance, Customer customer){
        this.cid=cid;
        this.balance=balance;
        this.customer=customer;
    }

    // ( 1 ) getInfo() , return String Type, which returns the details of the card    No. cid , balance balance The user to which it belongs Customer
    public String getinfo(){
        String info = " Card number "+cid+"\n Balance "+balance+"\n Users "+customer.getName();
         return info;
    }
    // Method of withdrawing money withdraw() The parameters are designed by ourselves, and if the money is withdrawn successfully, it will be returned true Failure returns false
    public boolean withdraw(int out_balance)
    {
        if (out_balance <= balance)
        {
            balance -= out_balance;
            return true;
        }

        return false;
    }

    // Method of saving money save() The parameters are designed by ourselves, and if the deposit is successful, it will return true Failure returns false  
    public boolean save (int in_banlance){
        if (in_banlance >=0){
            balance += in_banlance;
            return  true;
        }
        return false;
    }


}

package test3;
// Among them Customer Class has attributes such as name, ID number, contact phone number, and home address   
public class Customer {
    private String name;
    private String idcard;
    private String call;
    private String adress;


    public String getName() {
        return name;
    }

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

    public String isIdcard() {
        return idcard;
    }

    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }

    public String getCall() {
        return call;
    }

    public void setCall(String call) {
        this.call = call;
    }

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }
    public Customer(){

    }
    public Customer(String name, String idcard,String call,String adress){
        this.name=name;
        this.idcard=idcard;
        this.call = call;
        this.adress=adress;
    }
    public String say(){
        String info = " Name "+name+"\n ID number "+idcard+"\n Telephone "+call+"\n Address "+adress;
        return info;
    }
}

To understand the reference class in the class is to write another one, so don't think too complicated.

Coordinate point

package test2;
// Definition 1 Classes that describe coordinate points 
//
//​           0 -- >X
//
//​          |
//
//​          |
//
//​          |                  P(X,Y)
//
//​          |
//
//​          |
//
//​          Y
//
//
//
// ( 1 ) Has the function of calculating the distance from the current point to the origin 
//
// ( 2 ) Find any 1 Point ( m , n ) 
//
// ( 3 ) Find any 1 Point ( Point p ) 
//
// ( 4 ) with coordinate point display function, display format ( x , y ) 
//
// ( 5 ) Provides a parameterless constructor and 1 Constructor with parameters 
public class test2 {
    public static void main(String[] args) {
        point w=new point(10,20);
        w.oxy();
        w.mnxy( 66,77 );
        w.ponitp( 14,16 );
        w.show();
    }
}
public class point {
    int x ;
    int y ;
    int m ;
    int n ;
    public int getM() {
        return m;
    }

    public void setM(int m) {
        this.m = m;
    }


    public int getN() {
        return n;
    }

    public void setN(int n) {
        this.n = n;
    }




    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }



    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
 public point(){

 }
 public point(int x , int  y){
        this.y=y;
        this.x = x;
 }

 public void  oxy(){
     System.out.println(Math.sqrt( x*x+y*y ));
 }
 // ( 2 ) Find any 1 Point ( m , n ) 
    public void mnxy (int m , int n ){
        this.m=m;
        this.n=n;
        System.out.println(Math.sqrt( ((m-x)*(m-x)+(n-y)*(n-y)) ));
    }
// ( 3 ) Find any 1 Point ( Point p ) 
    public void ponitp (int z , int k ){
        System.out.println(Math.sqrt( ((z-x)*(z-x)+(k-y)*(k-y)) ));
    }

// ( 4 ) with coordinate point display function, display format ( x , y ) 
    public void show(){
        System.out.println( "("+x+","+y+")" );
    }

}

Random number sorting of students

// An highlighted block
var foo = 'bar';package test1;
// Defining a class Student , including 3 Attributes: Student number number(int) Grade state(int) , results  score(int) . 
// Create 20 Student object, student number is 1 To 20 Grade and grade are determined by random numbers. 
// Problem 1 : Print out 3 Grade (state Value is 3 ). 
// Problem 2 Sort students by grade using bubble sort and traverse all student information 
// Hint:  1)  Generate random numbers: Math.random() Return value type double;   ( Matn Is a tool class) ( [0,1} ) 
//	  2) 4 Shed 5 Enter rounding: Math.round(double d) The return value class long  Type 
public class demo5 {
    public static void main(String[] args) {
        Students [] stu = new Students[20];
        for (int i = 0; i < stu.length; i++) {
            // Assign values to array elements 
            stu[i]=new Students();
            // To Student Property assignment of the object of 
            stu[i].number = i +1;// Student number 
            stu[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);//(6  + 1));// Grade [1,6]
            stu[i].score = (int)(Math.random() *  (100 - 0 + 1));//(100 - 0 + 1));// Achievement [0,100]
        }
        // Traversing an array of students 
        for (int i = 0; i < stu.length; i++) {
            //System.out.println(stu[i].number + "," + stu[i].state + ","
            //		+ stu[i].score);
            System.out.println(stu[i].info());
        }
        System.out.println("*******************");
        // Problem 1 : Print out 3 Grade (state Value is 3 ). 
        for (int i = 0; i < stu.length; i++) {
            if (stu[i].state == 3) {
                System.out.println(stu[i].info());
            }
        }
        System.out.println( "\t");
        // Problem 2 : Use bubble sorting to sort students by grade and traverse all student information. 
        for (int i = 0; i < stu.length - 1; i++) {
            for (int j = 0; j < stu.length - 1 - i; j++) {
                if(stu[j].score > stu[j + 1].score){
                    // If you need to change the order, you exchange the elements of the array. Student Object! ! ! 
                    Students temp = stu[j];
                    stu[j] = stu[j + 1];
                    stu[j + 1] = temp;

                }
            }
        }
        for (int i = 0; i < stu.length; i++) {
            System.out.println(stu[i].info());
        }
    }
}
public class Students {
    // Student number number(int) Grade state(int) , results  score(int) . 
     int number;
     int state;
      int  score;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
    public String info(){
        return " Student number: " + number + ", Grade: " + state + ", Achievement " + score;
    }




Related articles: