JAVA Foundation-Chapter 6 Classes and Objects, Encapsulation, and Construction Methods

Today's content

Object
- oriented class and object
three major characteristics-encapsulation
construction method

teaching objectives

Able to understand object-oriented thinking
Able to clarify the relationship between a class and an object
Able to master the definition format of a class Able to master the format
of creating an object and access the members in the class
Able to complete the exercises of the mobile phone class
Able to understand the memory diagram of the object
Able to speak member variables and local variables The difference

能够理解private关键字的含义
能够说出this关键字可以解决的问题
能够理解构造方法的含义
能够用封装的思想定义一个标准类

Chapter 1 Object-Oriented Thinking

1. 1 Overview of object-oriented thinking

Overview

Java language is an object-oriented programming language, and object-oriented thinking is a kind of programming thinking. Under the guidance of object-oriented thinking, we
use Java language to design and develop computer programs. The object here refers to all things in reality, and each thing has its own attributes and behaviors. The
object - oriented thinking refers to
the design thinking of computer events by abstracting the attributes and behavior characteristics of things by referring to things in reality in the process of computer programming . It is different from the process-oriented thinking, which emphasizes the realization of the function by calling the behavior of the object, rather than the step-by-step
operation.

For example

Laundry:

Facing the process: take the clothes off -> find a basin -> put some washing powder -> add some water -> soak for 10 minutes -> knead -> wash the clothes -> wring dry -> dry

stand up

Object-oriented: take the clothes off -> turn on the fully automatic washing machine -> throw the clothes -> button -> hang up

the difference:

Process-oriented: Emphasize steps.
Object-oriented: Emphasize the object, the object here is the washing machine.

Features

Object-oriented thinking is a kind of thinking that is more in line with our thinking habits. It can simplify complex things and transform us from executors to commanders.
The object-oriented language contains three basic characteristics, namely encapsulation, inheritance and polymorphism.

1. 2 classes and objects

Looking around, you will find many objects, such as tables, chairs, classmates, teachers, etc. Tables and chairs belong to office supplies, and teachers and students are all human beings. So what is

Class? What is an object?

What is a class

Class: is a collection of related attributes and behaviors. It can be regarded as a template of a class of things, using the attribute characteristics and behavior characteristics of things to describe the

Class things.

In reality, describe a class of things:
attributes: the status information of the things.
Behavior: what the thing can do.

Example: kitten.

Attributes: name, weight, age, color. Behavior: walking, running, calling.

What is an object

Object: It is the concrete embodiment of a class of things. The object is an instance of the class (the object is not to find a girlfriend), and it must have the attributes of this type of thing

And behavior.

In reality, an instance of a class of things: a kitten.

Example: a kitten.

Attributes: tom, 5 kg, 2 years, yellow. Behaviours: walking around the wall, jumping and running, meowing.

The relationship between class and object

Class is a description of a class of things and is abstract.
Objects are instances of a class of things and are concrete.
The class is the template of the object, and the object is the entity of the class.

1. Definition of 3 categories

Comparison of things and classes

A class of things in the real world:

Attributes: the status information of things. Behavior: What things can do.

The same is true for describing things with class in Java:

Member variables: corresponding to the properties of things Member methods: corresponding to the behavior of things

Class definition format

Definition class: It is to define the members of the class, including member variables and member methods.
Member variable: It is almost the same as the previously defined variable. Only the location has changed. In the class, outside the method.

成员方法:和以前定义方法几乎是一样的。只不过把static去掉,static的作用在面向对象后面课程中再详细
讲解。

Examples of class definition format:

public class ClassName {
//成员变量
//成员方法
}
public class Student {
//成员变量
String name;//姓名
int age;//年龄

1. 4 Use of objects

Object format

Create an object:

Use objects to access members of a class:

Examples of object usage formats:

//Member method

//learning method

publicvoid study() {
System.out.println("好好学习,天天向上");
}
//吃饭的方法
publicvoid eat() {
System.out.println("学习饿了要吃饭");
}
}
类名 对象名 = new 类名();

Object name. Member variable;

Object name. Member method ();

public class Test 01 _Student {
public static void main(String[] args) {
//创建对象格式:类名 对象名 = new 类名();
Student s = new Student();
System.out.println("s:"+s); //cn.itcast.Student@ 100363
//直接输出成员变量值
System.out.println("姓名:"+s.name); //null
System.out.println("年龄:"+s.age); // 0
System.out.println("‐‐‐‐‐‐‐‐‐‐");
//给成员变量赋值
s.name = "赵丽颖";
s.age =  18 ;
//再次输出成员变量的值
System.out.println("姓名:"+s.name); //赵丽颖
System.out.println("年龄:"+s.age); // 18
System.out.println("‐‐‐‐‐‐‐‐‐‐");
//调用成员方法
s.study(); // "好好学习,天天向上"
s.eat(); // "学习饿了要吃饭"
}

Data type default value

基本类型 整数(byte,short,int,long) 0
浮点数(float,double) 0. 0
字符(char) '\u 0000 '
布尔(boolean) false
引用类型 数组,类,接口 null

Default value of member variable

1. Exercises for 5 categories and objects

Define the phone class:

Define the test class:

}

public class Phone {
// 成员变量
String brand; //品牌
int price; //价格
String color; //颜色
// 成员方法
//打电话
public void call(String name) {
System.out.println("给"+name+"打电话");
}
//发短信
public void sendMessage() {
System.out.println("群发短信");
}
}
public class Test 02 Phone {
public static void main(String[] args) {
//创建对象
Phone p = new Phone();
//输出成员变量值
System.out.println("品牌:"+p.brand);//null
System.out.println("价格:"+p.price);// 0
System.out.println("颜色:"+p.color);//null
System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐");

1. 6 Object Memory Diagram

An object, call a method memory graph

通过上图,我们可以理解,在栈内存中运行的方法,遵循"先进后出,后进先出"的原则。变量p指向堆内存中
的空间,寻找方法信息,去执行该方法。
但是,这里依然有问题存在。创建多个对象时,如果每个对象内部都保存一份方法信息,这就非常浪费内存
了,因为所有对象的方法信息都是一样的。那么如何解决这个问题呢?请看如下图解。

Two objects, call the same method memory graph

//Assign member variables

p.brand = "锤子";
p.price =  2999 ;
p.color = "棕色";
//再次输出成员变量值
System.out.println("品牌:"+p.brand);//锤子
System.out.println("价格:"+p.price);// 2999
System.out.println("颜色:"+p.color);//棕色
System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐");
//调用成员方法
p.call("紫霞");
p.sendMessage();
}
}

When an object calls a method, it searches for method information in the class according to the method tag (address value) in the object. So even if there are multiple objects, method information

Save only one copy, saving memory space.

A reference, passed as a parameter to the memory graph in the method

The reference type is used as a parameter, and the address value is passed.

1. 7 The difference between member variables and local variables

Depending on where the variables are defined, we have given them different names. As shown below:

Different positions in the class focus

Member variables: in the class, outside the method

Local variables: in the method or on the method declaration (formal parameters)

The scope is different

Member variables: in the class

Local variables: method

Different points of initialization value

Member variables: have default values

Local variable: There is no default value. Must be defined, assigned, and finally used

Different locations in memory understand

Member variable: heap memory

Local variables: stack memory

Different understanding of life cycle

Member variables: exist as the object is created, and disappear as the object disappears

Local variables: exist as the method is called, and disappear as the method is called

Chapter 2 Packaging

2. 1 Package overview

Overview

Object-oriented programming language is a simulation of the objective world. In the objective world, member variables are hidden inside the object and cannot be directly manipulated or modified by the outside world.

Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being randomly accessed by other classes. To access this type of data, you must pass the specified

the way. Proper encapsulation can make the code easier to understand and maintain, and it also enhances the security of the code.

in principle

Hide the properties, if you need to access a property, provide a public method to access it.

2. 2 encapsulation steps

2. 2 encapsulation steps

1. 使用 private 关键字来修饰成员变量。
2. 对需要访问的成员变量,提供对应的一对 getXxx方法 、setXxx 方法。

2. 3 encapsulated operation-private keyword

The meaning of private

1. private是一个权限修饰符,代表最小权限。
2. 可以修饰成员变量和成员方法。
3. 被private修饰后的成员变量和成员方法,只在本类中才能访问。

Private usage format

1. 使用 private 修饰成员变量,代码如下:
2. 提供 getXxx方法 / setXxx 方法,可以访问成员变量,代码如下:

2. 4 Packaging optimization 1-this keyword

private 数据类型 变量名 ;
public class Student {
private String name;
private int age;
}
public class Student {
private String name;
private int age;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
}

We found that the formal parameter names in the setXxx method do not meet the requirements of the name-knowledge, so if the modification is consistent with the member variable name, will it
be the same? code show as below:

After modification and testing, we found a new problem, the member variable assignment failed. In other words, after modifying the formal parameter variable name of setXxx(), the
method did not assign a value to the member variable! This is because the name of the formal parameter variable and the name of the member variable are the same, which causes the member variable name to be hidden, the variable name in the method cannot
access the member variable, and the assignment fails. Therefore, we can only use this keyword to solve this duplication problem.

the meaning of this

This represents the reference (address value) of the current object of the class, that is, the object's own reference.

记住 :方法被哪个对象调用,方法中的this就代表那个对象。即谁在调用,this就代表谁。

this format

Use this to modify the variables in the method to solve the problem of member variables being hidden. The code is as follows:

public class Student {
private String name;
private int age;
public void setName(String name) {
name = name;
}
public void setAge(int age) {
age = age;
}
}
this.成员变量名;
public class Student {
private String name;
private int age;
public void setName(String name) {
//name = name;
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
//age = age;
this.age = age;
}
public int getAge() {
return age;
小贴士:方法中只有一个变量名时,默认也是使用 this 修饰,可以省略不写。

2. 5 Packaging Optimization 2-Construction Method

When an object is created, the constructor is used to initialize the object and assign initial values ​​to the member variables of the object.

小贴士:无论你与否自定义构造方法,所有的类都有构造方法,因为Java自动提供了一个无参数构造方法,
一旦自己定义了构造方法,Java自动提供的默认无参数构造方法就会失效。

Definition format of construction method

In the way of writing the construction method, the method name is the same as the name of the class it is in. It has no return value, so it does not need a return value type, or even void. After using the
constructor, the code is as follows:

Precautions

1. If you do not provide a construction method, the system will give a parameterless construction method.

2. If you provide a construction method, the system will no longer provide a parameterless construction method.

3. The construction method can be overloaded, either with or without parameters.

2. 6 standard code-JavaBean

JavaBean is a standard specification for classes written in the Java language. A class conforming to JavaBean requires that the class be specific and public, and have a
parameterless construction method, and provide set and get methods to manipulate member variables.

}

}

Modifier construction method name (parameter list) {

// method body

}

public class Student {
private String name;
private int age;
// 无参数构造方法
public Student() {}
// 有参数构造方法
public Student(String name,int age) {
this.name = name;
this.age = age;
}
}

Write a class that conforms to the JavaBean specification. Take the student class as an example. The standard code is as follows:

The test class, the code is as follows:

public class ClassName{
//成员变量
//构造方法
//无参构造方法【必须】
//有参构造方法【建议】
//成员方法
//getXxx()
//setXxx()
}
public class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student() {}
public Student(String name,int age) {
this.name = name;
this.age = age;
}
//成员方法
publicvoid setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
publicvoid setAge(int age) {
this.age = age;
}
publicint getAge() {
return age;
}
}
public class TestStudent {
public static void main(String[] args) {
//无参构造使用
Student s= new Student();
s.setName("柳岩");
s.setAge( 18 );
System.out.println(s.getName()+"‐‐‐"+s.getAge());

//Use with parameter structure

Student s 2 = new Student(“赵丽颖”, 18 );
System.out.println(s 2 .getName()+"‐‐‐"+s 2 .getAge());
}
}

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/108198375