The core of Java syntax - object-oriented programming

Table of contents

An overview of process-oriented thinking

Overview of object-oriented thinking

Characteristics and examples of object-oriented thinking

The relationship between classes and objects

Class definition

Cases of classes and objects (demo02)

 Object memory storage mechanism

 The difference between member variables and local variables

 private keyword

encapsulation

Edit

this keyword

Edit

Construction method

​Edit 

Code writing and testing of standard classes

 Object-oriented standard case-student class

An overview of process-oriented thinking

  • Let’s think back on the steps we took to complete a requirement in the past few days:The first stepis to figure out what we want to do, Thenanalysehow to do it, Finallywe Reflected in code. Implement it step by step, and each specific step requires us to implement and operate. These steps call and cooperate with each other to complete our needs.
  • We are participants in every specific step above, and we need to face every specific step and process. This is the most direct embodiment of being process-oriented.
  • So what is process-oriented development? Process-oriented development is actually oriented to each specific step and process, completing each step and process, and then these functional methods call each other to complete the requirements.
  • Representative process-oriented language: Clanguage, assembly language

Overview of object-oriented thinking

        When the demand is single or simple, we can do it step by step without any problem, and the efficiency is quite high. But as the needs changed and the functions increased, I found that it was troublesome to face every step. Then I started to think about whether these steps and functions could be encapsulated. When encapsulating, perform different encapsulation according to different functions. Similar functions are packaged together. This makes the structure much clearer. When using it, just find the corresponding class. This is object-oriented thinking.

Characteristics and examples of object-oriented thinking

  • Characteristics of object-oriented thinking

        – is a thought that is more in line with our thinking habits

        –Can simplify complex things

        –Changeus from executors to commanders

  • Roles have changed
  • Examples of object-oriented thinking(demo01)

        –Buy a computer

        Process-oriented: I want to buy a computer - I want to clarify the meaning of buying a computer - check the corresponding parameter information online - go to Zhongguancun to buy a computer - bargain for a price - buy back the computer

        Object-oriented: I want to buy a computer - the monitor went to buy me a computer - bought the computer back

        –Washing clothes

        Process-oriented: Take off the clothes - find a basin - put some laundry detergent - add some water - soak for 10 minutes - knead - wash the clothes - wring them dry - hang them up

        ​​ Object-oriented: Take off the clothes - open the fully automatic washing machine - throw the clothes - button - dry the clothes

The relationship between classes and objects

  • We learn programming languages ​​in order to simulate things in the real world and achieve informatization. For example: the billing system for shopping in the supermarket, and the system for doing business at the bank.
  • How do we represent a real-world thing:

        –Attributes  is the description information of the thing

        –Behavior  is what the thing can do

        –举Example: Student affairs

  • The Java we are learningThe most basic unit of the language is a class, so we should use a class to represent things.
  • Class: is a collection of related properties and behaviors
  • Object: It is the specific embodiment of this type of thing
  • Example:

        –  Student

        –Object  The squad leader is an object

Class definition

  • real world things

        –Attributes  Descriptive information (variables) of things

        –Behavior  What a thing can do (method)

  • The same is true for usingclass to describe things in Java

        –Member variables  are attributes of things

        –Member method  is the behavior of things

  • Defining a class is actually defining the members of the class (Member variables and member methods)

Case study of classes and objects(demo02)

  • Student category

        –How determined

  • Analyze step by step according to the process from things to categories

        –How to use

  • Create object:

        –Class name Symbol name = new Class name ();

  • Elephant name.Amount of change
  • Object name.Member method ()

The object actually corresponds to a memory address

Student category

Class:Student.java

package com.demo02;
/**
 * 
 * @author 无限嚣张(菜菜)
 * 类的定义:类是用来描述现实世界的事务
 *事物:
 *		属性  事物的描述信息
 *		行为  事物能够做什么
 *类是如何和事物进行对应的?
 *		类:
 *			成员变量
 *			成员方法
 *需求:写一个学生类
 *学生事物:
 *		属性:姓名,年龄...
 *		行为:学习,吃饭...
 *学生类:
 *		成员变量:姓名,年龄
 *		成员方法:学习,吃饭
 *成员变量:和我们之前学的变量定义一样
 *		位置不同:类中,方法外
 *		初始化值:不需要给初始化值
 *成员方法:和我们之前学的方法是一样的,去掉static
 */
public class Student {
	//成员便令
	//姓名
	String name;
	//年龄
	int age;
	
	//成绩
	float score;
	
	//成员方法
	//学习方法
	public void study() {
		System.out.println("好好学习,天天向上");
	}
	
	//吃饭的方法
	public void eat() {
		System.out.println("学习饿了,要吃饭");
	}
}

Main function: StudentDemo.java

package com.demo02;
/*
学生类
        –如何定义

按照事物到类的过程一步步分析
        –如何使用

创建对象:
        –类名 对象名 = new 类名();

对象名.成员变量
对象名.成员方法
 */
public class StudentDemo {
	public static void main(String[] args) {
		//格式:类名 对象名 = new 类名();  s是学生类的对象
		Student s = new Student();
		System.out.println("s:"+s); //com.demo02.Student@193c0cf
	
		//直接输出成员变量值ֵ
		System.out.println("姓名:"+s.name); //null
		System.out.println("年龄:"+s.age); //0
		System.out.println("成绩:"+s.score); //0
		System.out.println("----------");
		
		//给成员变量赋值ֵ
		s.name = "小花";
		s.age = 28;
		s.score = 65.5f;
		
		//再次输出成员变量值ֵ
		System.out.println("姓名:"+s.name); //小花
		System.out.println("年龄:"+s.age); //28
		System.out.println("成绩:"+s.score); //0
		System.out.println("----------");
		
		//调用成员方法
		s.study();
		s.eat();
	}
}

Results demonstration

Mobile phone category 

Create class: phone.java

package com.demo02;
/*
 * 手机类
 * 		成员变量:品牌、价格、颜色
 * 		成员方法:打电话、发短信
 */
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 void sendMessage(String name) {
		System.out.println("给"+name+"发短信");
	}
}
package com.demo02;
/*
 * 手机类的测试类
 */
public class PhoneDemo {
	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("------------");
		
		//给成员变量赋值ֵ
		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();
		p.sendMessage("小花");
	}
}

 Object memory storage mechanism

  • Memory for 1 objects

        –The basic initialization process of an object

  • 2 objects of memory

        –methodological sharing

  • Memory for 2 objects

        –Two references point to the same object

1 object of memory

The class has been created before, so I won’t repeat it here!

package com.demo03;

/*
 * 手机类的测试类
 */
public class PhoneDemo {
	public static void main(String[] args) {
		Phone p = new Phone();
		System.out.println("p:"+p);
		System.out.println(p.brand + "---" + p.price + "---" + p.color);
		
		p.brand = "华为";
		p.price = 2999;
		p.color = "红色";
		
		System.out.println(p.brand + "---" + p.price + "---" + p.color);
		
		p.call("张三");
		p.sendMessage();
	}
}

 Memory for 2 objects (two different objects, different memory addresses)

package com.demo03;
/*
 * 手机类的测试类
 */
public class PhoneDemo2 {
	public static void main(String[] args) {
		Phone p = new Phone();
		p.brand = "小米5S";
		p.price = 1999;
		p.color = "银色";
		System.out.println("p:"+p);
		System.out.println(p.brand+"---"+p.price+"---"+p.color);
		p.call("张三");
		p.sendMessage();
		
		Phone p2 = new Phone();
		p2.brand = "IPhone7S";
		p2.price = 7999;
		p2.color = "土豪金";
		System.out.println("p2:"+p2);
		System.out.println(p2.brand+"---"+p2.price+"---"+p2.color);
		p2.call("林黛玉");
		p2.sendMessage();
	}
}

 3.Two references point to the same object (the memory address and value are exactly the same)

package com.demo03;
/*
 * 手机类的测试类
 */
public class PhoneDemo3 {
	public static void main(String[] args) {
		Phone p = new Phone();
		p.brand = "OPPO";
		p.price = 2999;
		p.color = "红色";
		System.out.println("p:"+p);
		System.out.println(p.brand+"---"+p.price+"---"+p.color);
		
		Phone p2 = p;			//把p的内存地址直接给了p2
		p2.brand = "华为";
		p2.price = 1999;
		p2.color = "黑色";
		System.out.println("再次输出p:"+p);
		System.out.println("p2:"+p2);
		System.out.println(p.brand+"---"+p.price+"---"+p.color);
		System.out.println(p2.brand+"---"+p2.price+"---"+p2.color);
	}
}

 The difference between member variables and local variables

  • Different positions in the class

        –Member variable outside the method in the class

        –Local variables within the method or on the method declaration

  • Different locations in memory

        –Member variable Heap memory

        –Local variable stack memory

  • different life cycles

        –Member variables exist with the existence of the object and disappear with the disappearance of the object

        –Local variables exist when the method is called and disappear when the method is called

  • Initialization values ​​are different

        –Member variables have default initialization values

        – Local variables have no default initialization value and must be defined and assigned before they can be used.

package com.demo04;

public class Variable {
	int x;//成员变量,有默认值
	
	public void show() {
		int y = 0;//局部变量,无默认值
		
		System.out.println(x);
		System.out.println(y);
	}
	
	public static void main(String[] args) {
		Variable variable = new Variable();
		variable.show();//类的方法
	}
}

 private关键字

  • private keyword:

        –This is oneRestricted training mark.

        –Can modify members(Member variables and member methods)

        –Members modified byprivate can only be accessed within this class< a i=4>.

  • The most common applications of private:

-

        –Provide the correspondinggetXxx()/setXxx () method (get is to obtain the value of age, and set is to assign a value to age)

        –The use of a standard case

kind:

package com.demo05;

public class Student {
	String name;
	//int age;
	private int age;
	
	public void setAge(int a) {
		if(a<0 || a>200) {
			System.out.println("你给的年龄有误");
		}else {
			age = a;
		}
	}
	
	/*	public int getAge() {
			return age;
		}*/
	
	public void show() {
		System.out.println("姓名是:"+name+",年龄是:"+age);
	}
}
package com.demo05;

public class StudentDemo {
	public static void main(String[] args) {
		//创建类
		Student s = new Student();
		s.show();
		
		s.name = "张三";
		//s.age = 28;
		//s.age = -28;
		//s.setAge(-28);
		s.setAge(28);
		s.show();
	}
}

 Tips: Click source - Generate Getters and Setters to automatically generate get and set methods, and just make modifications as needed.

encapsulation

  • Package overview

        – is one of the three major characteristics of object-oriented . (The other two are inheritance and polymorphism)

        – is a simulation of the objective world by object-oriented programming language. In the objective world, member variables are hidden inside the object and cannot be accessed by the outside world. Direct manipulation and modification. Just like the age mentioned earlier.

  • Packaging principles:

        –Hide content that does not need to be provided to the outside world.

        – hides the properties and provides public methods to access them.

                •Member variableprivate, provides the corresponding getXxx ()/setXxx() method

  • benefit:

        –Use methods to control the operation of member variables, which improves the security of the code

        –Encapsulate the code with methods to improve the reusability of the code

kind:

package com.demo06;
/*
 * 学生类
 */
public class Student {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

Test class:

package com.demo06;
/*
 * 学生类测试类
 */
public class StudentDemo {
	public static void main(String[] args) {
		//创建对象
		Student s = new Student();
		// 获取名字和年龄
		System.out.println(s.getName()+"——————"+s.getAge());
		
		// 给名字和年龄赋值
		s.setName("小花");
		s.setAge(48);
		System.out.println(s.getName()+"——————"+s.getAge());
	}
}

this关键字

  • this: represents the object reference of the class it belongs to
  • remember:

        – Which object the method is called, this represents which object

  • When to use this?

        –Local variables hide member variables

kind:

package com.demo07;
/*
 * 学生类
 * 
 * 起名字我们要求做到见名知意
 * 而我们现在的代码中的n和a就没有做到见名知意,我们要改进
 * 
 * 如果有局部变量和成员变量名字相同时,在局部使用时,采用的是就近原则
 * 
 * 我们有没有办法把局部变量的name赋值给成员变量name呢?
 * 有
 * 
 * 什么办法呢?
 * 		用this关键字就可以解决这个问题
 * 
 * this:代表所在类的对象引用
 * 		方法被哪个对象调用,this就代表哪个对象
 * 
 * 使用场景
 * 		局部变量隐藏成员变量
 */
public class Student {
	private String name;
	private int age;
	
	public void setName(String name) { 
		//name = n;
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setAge(int age) {
		//age = age;
		this.age = age;
	}
	
	public int getAge() {
		return age;
	}
}

Test class

package com.demo07;
/*
 * 学生类
 */
public class StudentDemo {
	public static void main(String[] args) {
		//创建对象
		Student s = new Student();
		System.out.println(s.getName()+"---"+s.getAge());
		
		s.setName("张三");
		s.setAge(28);
		System.out.println(s.getName()+"---"+s.getAge());
	}
}

Construction method

  • Overview of the role of constructor methods

        –Initialize the object’s data

  • Constructor format

        –The method name is the same as the class name

        – has no return value type, not even void

        –No specific return value

  • Notes on construction methods

        –If you do not provide a constructor, the system will provide a default constructor

        –If you provide a constructor, the system will no longer provide it

        –Constructor methods can also be overloaded

kind:

package com.demo08;


public class Student {
	private String name;
	private int age;
	

	
	public Student() {}
	
	public Student(String name) {
		this.name = name;
	}
	
	public Student(int age) {
		this.age = age;
	}
	
	public Student(String name,int age) {
		this.name = name;
		this.age = age;
	}

	public void show() {
		System.out.println(name+"---"+age);
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
}

Test class

package com.demo08;

public class StudentDemo {
	public static void main(String[] args) {

		Student s4 = new Student("小花",28);
		s4.show();
	}
}

 

Code writing and testing of standard classes

  • kind

        –Amount of staff change

        –Construction method

                •No-access construction method

                •Construction method with parameters

        –Member method

                •getXxx()

                •setXxx()

  • How to assign values ​​to member variables

        ;

        ​​​Construction method with parameters

kind:

package com.demo09;
/*
 * 学生类
 */
public class Student {
	/**成员变量——姓名*/
	private String name;
	/**成员变量——年龄*/
	private int age;
	
	/**构造方法*/
	public Student() {}
	/**构造方法*/
	public Student(String name,int age) {
		this.name = name;
		this.age = age;
	}
	
	/**给姓名赋值*/
	public void setName(String name) {
		this.name = name;
	}
	
	/**
	 * 获取姓名
	*/
	public String getName() {
		return name;
	}
	
	/**
	 * 给年龄赋值ֵ
	 * @param age
	 */
	public void setAge(int age) {
		this.age = age;
	}
	
	/**
	 * 获取年龄
	 * @return age
	 */
	public int getAge() {
		return age;
	}
}

Test class:

package com.demo09;
/*
 * 测试类
 */
public class StudentDemo {
	public static void main(String[] args) {
		//构造方法
		Student s = new  Student();
		s.setName("小花");
		s.setAge(28);
		System.out.println(s.getName()+"---"+s.getAge());
		
		//赋值
		Student s2 = new Student("小花",28);
		System.out.println(s2.getName()+"---"+s2.getAge());
	}
}

 Object-oriented standard case-student class

Class: student.java

package com.demo10;

public class Student {
	/**
	 * 学生类
	 */
	
	// 方法
	public void study() {
		System.out.println("好好学习");
	}
}

Class: teacher.java

package com.demo10;

public class Teacher {
	/**
	 *调用学生类的学习方法 
	 * @param s 学生对象
	 */
	public void test(Student s,Yu d) {
		s.study();
		d.zy();
	}
}

Class: yu.java

package com.demo10;

public class Yu {
	public void zy() {
		System.out.println("天天向上");
	}

}

Test class:

package com.demo10;

//需求:调用teacher的test方法

//类名作为形式参数
public class Test {
	public static void main(String[] args) {
		Teacher t = new Teacher();
		Student s = new Student();
		Yu q = new Yu();
		t.test(s,q);
	}
}

 

 kind:

package com.demo11;

public class Student {
	public void study() {
		System.out.println("好好学习,天天向上");
	}
}

kind:

package com.demo11;

public class Teacher {
	
	public Student getStudent() {
		Student s = new Student();
		return s;
	}
}

Test class

package com.demo11;

//需求:通过Teacher得到Student对象,然后调用Student类的方法
//如果方法的返回值是类名,其实返回的是该类的对象
public class Test {
	public static void main(String[] args) {
		Teacher t = new Teacher();
		Student s = t.getStudent();
		//Student s = new Student();
		s.study();
	}
}

 

Guess you like

Origin blog.csdn.net/zywcxz/article/details/128772508