Java Zero Foundation Series Tutorial 10 Java Abstraction and Encapsulation

Supporting video tutorial

This article B station supporting video tutorial

The purpose of the software

Describe the real world in computer language
Solve real-world problems with computers

Why use object orientation

The world consists of objects

Object-Oriented Thought Description Object-Oriented World Conforms to Human Thinking Habits

There are three steps to abstracting classes from reality:

  1. find out its kind
  2. find out its properties
  3. find out its behavior

Describe the world with object orientation

Step 1: Discover the class
class Dog {

}
Abstract "class" from "object"

Step 2: Discover the properties of the class
Features common to dogs:

  1. Variety
  2. age
  3. Nick name
  4. health condition
  5. intimacy with the owner
    ... ...
class Dog { 
    String name = "Prosperity"; // Nick name
    int health = 100; // health value    
    int love = 0;   // intimacy
    String strain = "labrador"; // Variety 
}

Only put business-related attributes

Step 3: Discover the methods of the class
Behaviors common to dogs:

  1. run
  2. bark
  3. output your own information
    ... ...
class Dog { 
    String name = "Prosperity";   // Nick name
    int health = 100; // health value    
    int love = 0;     // intimacy
    String strain = "labrador"; // Variety 
    /* output dog information */
    public void print() {
        // code to output dog information
    } 
}

Only put business-related methods

Describe classes using class diagrams

practice

Implement pet adoption
Write pet classes Dog and Penguin
Create a pet object, enter the adopted pet information and output

object initialization

Penguin pgn = new Penguin();
pgn.name = "qq";
pgn.sex = "Q young"; 

Can the assignment be done at the same time as the object is created?

Use the constructor:
Penguin pgn1 = new Penguin();

class Penguin {
    // Attributes
    /* No-argument constructor */
    public Penguin() {
           name = "qq";
           love = 20;
           sex = "Q young";
           System.out.println("execute constructor");
    }
}

Construction method

The system provides a default no-argument constructor

public Penguin() {

}

custom constructor

public Penguin () {
        name = "qq";
        love = 20;
        sex = "Q young";
}

public Penguin (String name,int health,int love,String sex ) {
        this.name = name;
        this.health = health;
        this.love = love;
        this.sex = sex;
}

The system no longer provides a default no-argument constructor

The this keyword is a default reference to an object, which is used to distinguish member variables of the same name

method overloading

System.out.println(45);
System.out.println(true);
System.out.println("Dogs are playing!"); 

call overloaded method

pgn = new Penguin();
pgn.print();
pgn = new Penguin("beautiful", 80, 20, "Q young");
pgn.print();

one example

class Penguin {
       String name = null; //Nick name
       int health = 0; // health value
       String sex = null; // gender
       public void Penguin() {	
               health=10;
               sex="male";
               System.out.println("execute constructor");
        }
        public void print() {
               System.out.println("penguin's name is" + name + ",health value is" 
                                                 + health + ",gender is" + sex);
        }
}

Penguin pgn3= new Penguin();
pgn3.print();

Find the problem with the code below

class Dog {
       private String name = "Prosperity";   // Nick name
       private int health = 100;  // health value    
       private int love = 0;     // intimacy	
       public void play(int n) {
              int localv;
              health = health - n;		
              System.out.println(name+" "+ localv +" "+health+" "+love); 
       }
       public static void main(String[] args) {
              Dog d=new Dog();
              d.play(5);
       }
} 

static static member

An example of counting the number of objects created

class Person
{
    public String name;
    public int age;
    static public long  all_count;
    public Person(){
        all_count++;
    }
    public Person( String name , int age ){
        all_count++;
        this.name = name;
        this.age = age;
    }
    // count function
    public long getCount(){
      return all_count;
    }
    // Should have the ability to find peers
    public boolean isSameAge( Person p1 ){
      return this.age == p1.age;
    }
}
class Demo9 
{
    public static void main(String[] args) 
    {
        Person p1 = new Person( "jame" ,  34 );
        Person p2 = new Person( "lucy" ,  34 );

        Person p3 = new Person( "lili" ,  34 );
        Person p4 = new Person();
        System.out.println( p1.getCount() + " " + p2.getCount() + "  " + p3.getCount()  );
        System.out.println( p1.isSameAge( p2 ) );
        System.out.println( p1.isSameAge( p3 ) );
    }
}

4: static features
1 is loaded as the class is loaded, static is loaded as the class is loaded, and disappears as the class disappears. Explain that its life cycle is very long.
2 takes precedence over object existence. —> Static state exists first, and object exists later
3 is shared by all instances (objects).
4 can be called directly by the class name

Defining methods using static

Call with class name: Person.print();

Static methods can only access static properties, not instance properties

find mistakes

class Dog {
       private String name = "Prosperity"; // Nick name
       private int health = 100;     // health value
       private int love = 0;        // intimacy		
       public void play(int n) {
              static int localv=5;		
              health = health - n;		
              System.out.println(name+" "+localv+" "+health+" "+love);
       }	
       public static void main(String[] args) {
              Dog d=new Dog();
              d.play(5);
       }
} 

package

Dog d = new Dog();
d.health = -1000;
Attribute random access, unreasonable assignment

The concept of encapsulation

Encapsulation: Hide some information of the class inside the class, and do not allow external programs to directly access it, but realize the operation and access to the hidden information through the methods provided by the class

The benefits of packaging

1. Hide the implementation details of the class
2. Data can only be accessed through prescribed methods
3. It is convenient to add control statements
4. Easy to modify and implement

packaging steps

class Dog {
    private String name = "Prosperity"; // Nick name
    private int health = 100; // health value
    private int love = 0;   // intimacy
    private String strain = "labrador"; // Variety
    public int getHealth() {
        return health;
    }
    public void setHealth (int health) {
        if (health > 100 || health < 0) {
            this.health = 40;
            System.out.println("Health value should be between 0 and 100, default value is 40");
        } else
            this.health  =  health;
    }
    // Other getter/setter methods
}

this

When a variable (object, instance) is defined with a class name, what is defined is just a reference, and the outside can access the properties and methods in the class through this reference.

So is there enough and should have a reference in the class to access its own properties and methods?

JAVA provides a very good thing, which is this object, which can refer to the properties and methods of this class in the class.
Let's start with a simple example:

public class ThisDemo {  
    String name="Mick";
    public void print(String name){
        System.out.println("properties in a class name="+this.name);
        System.out.println("local parameter properties="+name);
    }   
    public static void main(String[] args) {
        ThisDemo tt=new ThisDemo();
        tt.print("Orson");
    }
}

"Thinking in Java" has a classic example of returning a reference to the class itself.
Return the object itself through this keyword and implement multiple operations in one statement

public class ThisDemo {  
    int number;
    ThisDemo increment(){
         number++;
         return this;
    }  
  private void print(){
         System.out.println("number="+number);
    }
    public static void main(String[] args) {
        ThisDemo tt=new ThisDemo();
         tt.increment().increment().increment().print();
    }
}

Two constructors are defined in a class, and the other constructor is called by this reference in one constructor

public class ThisDemo {  
    String name;
    int age;
    public ThisDemo (){ 
        this.age=21;
   }     
    public ThisDemo(String name){
        this();
        this.name="Mick";
    }     
  private void print(){
         System.out.println("final name="+this.name);
         System.out.println("final age="+this.age);
    }
    public static void main(String[] args) {
       ThisDemo tt=new ThisDemo("zhangsan"); //Arbitrary parameters passed in
       tt.print();
    }
}

Exercise

Create the Dog class
Write the Test class

package com.company;

/**
 * Created by ttc on 2017/12/28.
 */
//private ,default, protected,public
public class Dog {
    private String name = "Prosperity"; // Nick name
    private int health = 100;     // Health value 0---100 private
    private int love = 0;        // intimacy
    private int type;//Type: 1 dog 2 penguin
    private int kind;//Variety

    public String toString()
    {
        String strKind = "";
        if(kind == 1)
        {
            strKind = "labrador";
        }
        else if(kind == 2)
        {
            strKind = "Schnauzer";
        }
        String str = "Confessions of a Pet, My Name Is"
                +name+"health value is"+health+"The intimacy with the master is"+love+"i am a"+strKind;
        return str;
    }

    public String getName() {
        return name;
    }

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

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public int getLove() {
        return love;
    }

    public void setLove(int love) {
        this.love = love;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public int getKind() {
        return kind;
    }

    public void setKind(int kind) {
        this.kind = kind;
    }
}


package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("welcome to pet store");
        System.out.println("Please enter pet name");

        String name = scanner.next();

        System.out.println("Please enter pet type:1 dog, 2 penguins");
        int type = scanner.nextInt();
        if(type == 1)
        {
            Dog d = new Dog();
            System.out.println("Please enter species,1 Smart Labrador, 2 Cool Schnauzers");
            int kind = scanner.nextInt();
            d.setKind(kind);
            d.setName(name);
            System.out.println(d);
        }
        else
        {
            //new penguin();
        }

    }
}

Create the Penguin class
Write the Test class

Posted by craygo on Thu, 30 Jun 2022 21:59:19 +0530