Encapsulation, inheritance,

Encapsulation, inheritance,

review

1 面向对象思想: 一种思维方式,着眼于找到一个具有特殊功能的具体个体,然后委托这个个体去做某件事情。

  面向过程思想:一种思维方式,着眼于解决问题的过程和步骤。

2 类的概念 : 一类具有相同属性和功能的实体的集合[群体]

3 对象:一个具体特殊功能的实体。

4 类和对象的关系:类是对象的抽象或模板,对象是类的具体或实例

5 定义类  

    public   class  Person{

        //成员变量  属性

        //方法

    }

6 创建对象 

    类名  对象名=new 类名();

    //使用对象的属性和方法

    对象名.属性名

    对象名.方法名(实参);

      对象的内存分配

      栈:空间比较小,存取速度快,特点:先进后出  jdk 1.5 256k  jdk1.5 1M

      堆:空间比较大,存取速度慢。

      方法区 (静态区,串池(常量池), 代码段)



7 构造方法:创建对象时调用的方法。

    public  类名(){

    }   

    默认构造方法

    带参构造方法 :初始化对象的属性

     构造方法重载 

8  this关键字  :表示当前对象的引用

    this.属性
        如果参数名和成员变量相同时,可以使用this.区分

    this.方法()

    this();//调用其他的构造方法
        this()只能用在构造方法中,必须是第一条语句
        this()只能调用一次

Today the task

1. 方法的参数传递和返回值
2. 封装
3. static
4. 继承
5. super
6. 包、访问权限修饰符
7. 方法重写

teaching objectives

1. 理解方法参数传递和返回值
2. 理解封装性
3. 掌握static关键字
4. 掌握继承
5. 掌握super
6. 理解包、访问权限修饰符
7. 掌握方法重写

Section I: Method of transmission parameters, return value

Java language is called upon to parameter assignment method used by value approach:

  • Basic types of data transfer that the data value itself.
  • Reference type of data transfer is also the value of the variable itself, i.e., address of the object (reference), rather than the object itself.
Transmitting the basic data types 1.1
//类
public class PassValue{
    public void change(int x){
        x = 100;
        System.out.println("方法中x==" + x);
    }
}

//类
public class Test{
     public static void main(String[] args){
        PassValue pv = new PassValue();
        int x = 5;
        System.out.println("方法调用之前x=="+ x);
        pv.change(x);
        System.out.println("方法调用之后x==" + x);
    }
}
1.2 reference data types passed

Array, class, String (special features: basic type and the same)

public class PassValue2{
    int x ;
    public void change(PassValue2 obj){
        obj.x = 100;
        System.out.println(“方法中obj.x==” + obj.x);
    }
}

public class Test{
   public static void main(String[] args){
        PassValue2 p = new PassValue2();
        p.x = 5;
        System.out.println(“方法调用之前p.x==” + p.x);
        p.change(p);
        System.out.println(“方法调用之后p.x==” + p.x);
    }
}

1-on Exercise:

编写学生类:

    学号,姓名,年龄,地址

    显示信息方法

编写学生管理类

    输入学生信息(学生作为方法返回值)

    修改学生信息(学生作为参数传递)
1.3 Basic types and reference type as the return value

The basic type of the actual data returned

Reference type returns the address of the object

Section II: Encapsulation

Java language has three characteristics:

  • Package (encapsulation): invisible to the outside, hidden object properties and implementation details.
  • Succession (inheritance): a class inherits a member of another class.
  • Polymorphism (Polymorphism): the diversity of each object represented.
1.1 Packaging concepts

What is encapsulation: class, who do not want to be outside the class member variables directly accessible, be privatized , the same time offer the public a way to access private members.

Package member variables two steps:

The first step: add private modifiers

Step two: Add the get and set methods

1.2 private

Use private member variables to achieve access to privatization, private member variable is modified private member variables can only be accessed directly within the class, the class can not directly access foreign

1.3 get and set methods

get representation method to access private property:

grammar:

public 属性类型 getXxx(){
      return 属性;
}

The method represents a modification method set value of the private property:

public void setXxx(参数类型 参数){
      this.xxx = 参数;
}
package com.qf.day09_4;
/**
 * 人类
 *  属性: 姓名 年龄 性别
 *  方法: eat study
 *  
 *  封装:(1)把成员变量变成私有的  (2)  添加get和set方法
 * @author wgy
 *
 */
public class Person {
    private String name;
    private int age;
    private String sex;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name=name;
    }
    
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        if(age>100||age<1) {
            this.age=18;
        }else {
            this.age=age;
        }
    }
    
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        if(sex.equals("男")||sex.equals("女")) {
            this.sex=sex;
        }else {
            this.sex="男";
        }
    }
    
    
    
    public void eat() {
        System.out.println(name+"开始吃饭...");
    }
    public void study() {
        System.out.println(name+"开始努力学习...");
    }
    public void show() {
        System.out.println("姓名:"+name+" 年龄:"+age+" 性别:"+sex);
    }
}
1.4 Class design principles
  • Member variables (attributes) privatization (with private modification), add the get and set methods
  • Discloses methods (using modified public)

Section III: static keyword

The static keyword can only modify class member: member variables and methods of modifying

Member variable (a static member variable (class variables, static properties), 2 non-static member variables (instance variables)), but in some cases, especially member variables instance variables.

2.1 static properties

All common and present the same object class attribute, a class of common variables, the object does not change with the change of the properties. For example: pi. Static property before the object is not dependent on the object, the class name can be directly accessed directly (class name attribute name) by.

public class Person{
    String name;
    int age;
    //人口总数
    static int totalCount = 1300000000;
}
public class DemoPerson{
    public static void main(String[]args){
        System.out.println(Person.totalCount);//Person类中的totalCount属性是一个静态属性,可以直接通过类名访问
    }
}
2.2 static method

All common and present the same class object a common method, belong to the class method, prior to the method object does not depend on the object, it can be directly invoked directly by the class name (the class name. Method name ()).

public class Person{
    static int totalCount;
    public static void calcTotalCount(){
        System.out.println("统计人口方法");
        totalCount=1350000000;
    }
}
public class DemoPerson{
    public static void main(String[]args){
        Person.calcTotalCount();
    }
}

Use static properties and methods using principles:

If this variable or a method, not every object belongs to the class, use a static modification.

2 If the object has only one, then the class properties and methods are static, the method of general tools category of static Arrays. Method name ()

Precautions :

1 static method can directly access a static variable, can not directly access non-static variables.

2 non-static method can access static variables and static methods directly.

There are three methods of static variables static domain zone

Code block 2.3

Code block is divided into: a partial code block, code block dynamic, static code block

Local code block: statement block of code in the method of execution timing associated with the position statement, released ahead of variables. (To understanding)

Dynamic block: automatically executed when a configuration is also called a code block or code blocks example, the class declaration code block body, to create objects, each created to perform a dynamic object is a block of code. Initialization. (To understanding)

Static code block: static keyword dynamic modification of the code block is automatically executed when the class is loaded and executed only once. (remember)

Section IV: inheritance

4.1 The concept of inheritance

On the basis of the original class, create a new class, the new class can access the original class of private non-members, and can add their own unique members, a process called succession, a simple understanding of a class that inherits another a class.

4.2 inheritance benefits
  • Reuse of code and extensions

  • Simulate real-world relationships

4.3 Use inherited class

The key to use extends inheritance relationship between two classes

Inherited class: the parent class, superclass, base class

Inherited class: subclass, derived class

Inheritance in line: is a relationship

4.4 syntax:
public class FatherClass{
    //属性
    //方法
}
public class ChildClass extends FatherClass {
    //属性
    //方法
}

1-on exercises

Write the Person class:

Properties include: date name, age, birth

Methods: showInfo ();

Student writing class:

Properties include: date name, age, birth, school

Methods: showInfo ();

​ study();

Student class using inheritance optimization.

public class Person {
    String name;
    int age;
    String birthday;
    
    public void showInfo() {
        System.out.println("姓名:"+name+" 年龄:"+age+" 出生日期:"+birthday);
    }
    
}

public class Student extends Person{
    
    String school;
    
  
    public void study() {
        System.out.println(name+"好好学习天天向上");
    }
}

2-on exercises:

Preparation of animal (name, color, variety), printing method, the preparation of the dog class (intimacy) and cats (Hobby) inherit animals, like dogs and cats have a print function information, the dogs have housekeeping method, there are cats playing ball method.

Animal category

package com.qf.day09_2;
/**
 * 动物类 
 *  (名字、颜色、品种),打印方法
 * @author wgy
 *
 */
public class Animal {
    //昵称
    String name;
    //颜色
    String color;
    //品种
    String strain;
    
    //打印信息
    public void print() {
        System.out.println("动物信息: 昵称:"+name+" 颜色:"+color+" 品种:"+strain) ;
    }
}

Dog class

package com.qf.day09_2;
/**
 * 狗狗类
 * @author wgy
 *
 */
public class Dog extends Animal{
    //亲密度
    int love;
    

    
    public void lookHome() {
        System.out.println(name+" 正在给主人看家...........");
    }
    
}

Cat class

package com.qf.day09_2;
/**
 * 猫类
 * @author wgy
 *
 */
public class Cat extends Animal{
    //爱好
    String hobby;
    
    /**
     * 玩球
     * 
     */
    public void playBall() {
        System.out.println(name+"正在玩球..........");
    }
}
4.5 subclass object instantiation
  • 1 parent class object to instantiate
    • The default constructor calls the parent class default
  • Examples of subclasses further objects 2
4.6 can not be inherited by subclasses of members:

1) Private Members: private member can not be inherited by subclasses
2) constructor: constructor of the parent class can not be inherited by subclasses, but will call the constructor method (default subclass first statement in the subclass constructor is call the default constructor of the parent class)

4.7 Inheritance features:

1) single inheritance: a subclass of only one parent class, a parent can have multiple children class
2) transitivity: inheritance is transitive

Section V: super keyword

5.1 super keywords: Use this and similar

this is a reference to the current object.

this usage:

Usage 1: Call this class of property, can solve the problem the same name as the name of the member variable name and local variables.

this. attribute name

Usage 2: Call this class method

this. method name

Usage 3: call other constructor in this class.

this (parameters);

Note: 1 can only be used in the construction process, the first statement must be

2 can be called only once

The concept of 5.2 super

super is a reference to the current parent object.

5.3 super usage rules

.. 1) super properties: indicates access the parent class attributes, when the sub-class defines the attributes with the same name as the parent class, To access the same name in the properties of the parent class subclass, super properties required access.

. 2) super Method: The method indicates that the call parent class, the subclass is the parent class is not rewritten to call, require the use of super method call.

3) super (): represents the constructor calls the parent class, pay attention: super () must be a subclass constructor in the first statement in
the subclass constructor defaults first statement calls the superclass no-argument constructor super constructor (), you may be manually call the parent class with a parameter

5.4 Exercises
public class Animal {
    //属性
    String nickname;
    String color;
    String strain;
    
    //默认构造方法
    public Animal() {
        System.out.println("父类Animal的构造方法执行了..........");
    }
    
    //带参构造方法()
    public Animal(String nickname,String color,String strain) {
        this.nickname=nickname;
        this.color=color;
        this.strain=strain;
    }
    
    
    //打印方法
    public void print() {
        System.out.println("本动物 昵称:"+nickname+" 颜色:"+color+" 品种:"+strain);
    }
}

public class Dog extends Animal{
    
    
    int love;
    //默认构造方法
    public Dog() {
        super();//调用父类的默认构造方法
        System.out.println("Dog子类的构造方法执行了");
    }
    //带参构造方法
    public Dog(String nickname,String color,String strain,int love) {
        super(nickname, color, strain);//调用父类的带参构造
        this.love=love;
    }
    
    
    public void lookHome() {
        System.out.println(nickname+"正在给主人看家....");
        System.out.println("昵称:"+super.nickname);
        System.out.println("颜色:"+super.color);
        System.out.println("品种:"+super.strain);
        System.out.println("亲密度:"+this.love);
        super.print();
    }
}

public class Test {
    public static void main(String[] args) {
        Dog afu=new Dog();
        afu.nickname="阿福";
        afu.color="黑色";
        afu.strain="哈士奇";
        afu.love=100;
        afu.lookHome();
        System.out.println("----------------------------------------");
        //调用Dog的带参构造
        Dog xiaohei=new Dog("小黑", "白色", "泰迪", 100);
        xiaohei.lookHome();
    }
}

and super this difference:

(1) this is a reference to the current object, super represents a reference current parent class object

(2) this. Property can call the current object's properties, including inherited properties, super. Properties can call the properties of the parent class

(3) this. Method () can call the current object's methods include inherited methods, super. Method () can call the parent's method

(4) this (parameters) to call other methods in this class constructor, super (parameters) to call the parent class constructor

(5) this (parameters) and super (parameters) can only be used in the construction process, the first statement must be called only once, can not be used simultaneously.

Section VI: Package

In order to facilitate the management of large software systems in a large number of classes, problem-solving class naming conflicts, Java introduces a package (package).

When using a lot of class, the class name and the method is difficult to decide. Sometimes necessary to use the same name for other classes. Package basically hides the class and avoids conflicts of names.

  • Declare packages with the package, package statement must be java source files in the first statement. (If this statement, it is left at unnamed package)
  • In the package statement, use "." To indicate the level package (directory). Package corresponds to the directory hierarchy of the file system.
  • The general use of the domain name company or organization inverted + project name or module name to represent the package name.
    • www.baidu.com wrapped name com.baidu.oa
    • www.alibaba.com package name com.alibaba.pay
6.1 Creating a Package
package com.qf.test;

public class Employee {
    private String name;        //姓名
    private int age;                //年龄
    private double salary;     //薪水

    public Employee(){
        
    }
    public Employee(String name, int age, double salary){    //构造方法
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    //getter和setter省略
 } 
Import Package 6.2

Using Java classes defined in different packages, the need to import statement introducing the required categories.

Syntax:

import package1[.package2…].类名

import com.qf.test.Employee;

public class PackageDemo {  
    public static void main(String args[]){
        Employee employee = new Employee();
    }
}

note:

To import all the classes in a package can be used: * package name.

For example: import java.util *;.

Class in the same package can refer to each other directly, without having to import statements.

Section VII: Access

Permissions \ range This class Class or package with the same type buns Different classes buns Different bags
public v v v v
protected v v v x
Default [default] v v x x
private v x x x
package a;
public class Person{
    public String name;
    protected int age;
    char sex;
    private double sal;
    public Person(){}
    public Person(String name, int age, char sex, double sal){
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.sal = sal;
    }
    public static void main(String[]args){
        Person p = new Person("张三", 12, 'm', 5000);
        System.out.println(p.name);
        System.out.println(p.age);
        System.out.println(p.sex);
        System.out.println(p.sal);
    }
}
package a;
public class Student extends Person{
    public static void main(String[]args){
        Person p = new Person("张三", 12, 'm', 5000);
        System.out.println(p.name);
        System.out.println(p.age);
        System.out.println(p.sex);
        //System.out.println(p.sal);//同包子类中无法访问父类中私有成员
    }
}

package a;
public class Demo{
    public static void main(String[]args){
        Person p = new Person("张三", 12, 'm', 5000);
        System.out.println(p.name);
        System.out.println(p.age);
        System.out.println(p.sex);
        //System.out.println(p.sal);//同包类中无法访问父类中私有成员
    }
}
package b;
public class Student extends Person{
    public static void main(String[]args){
        Person p = new Person("张三", 12, 'm', 5000);
        System.out.println(p.name);
        System.out.println(p.age);
        //System.out.println(p.sex);//不同包中子类中无法访问默认权限成员
        //System.out.println(p.sal);
    }
}

package b;
public class Demo{
    public static void main(String[]args){
        Person p = new Person("张三", 12, 'm', 5000);
        System.out.println(p.name);
        //System.out.println(p.age);//不同包中不能访问受保护属性
        //System.out.println(p.sex);
        //System.out.println(p.sal);//不同包类中无法访问父类中私有成员
    }
}

Use principles:

  • When modifying class: only public or default
  • Member variables and methods of modification: You can use public, default, protected, private
  • Local variables can not access modifier.

VIII: The method of rewriting (overwriting)

Method overloading (overload):

1 the same class, the same method name, a list of different parameters (different numbers, different types, different order)

2 and return values, independent of the access modifier.

8.1 method overrides
    在继承过程中,子类中从父类继承来的方法无法满足自己的需求时,可以在子类中对父类方法进行完善,这个完善过程叫做方法重写(override),方法的重写相当于在子类中覆盖父类中的方法。  

Case:

public class Animal {
    //属性
    String nickname;
    String color;
    String strain;
    
    //默认构造方法
    public Animal() {
        System.out.println("父类Animal的构造方法执行了..........");
    }
    
    //带参构造方法()
    public Animal(String nickname,String color,String strain) {
        this.nickname=nickname;
        this.color=color;
        this.strain=strain;
    }
    
    
    //打印方法
    protected Object printInfo() {
        System.out.println("本动物 昵称:"+nickname+" 颜色:"+color+" 品种:"+strain);
        return 10;
    }
}


public class Dog extends Animal{
    
    
    int love;
    //默认构造方法
    public Dog() {
        super();//调用父类的默认构造方法
        System.out.println("Dog子类的构造方法执行了");
    }
    //带参构造方法
    public Dog(String nickname,String color,String strain,int love) {
        super(nickname, color, strain);//调用父类的带参构造
        this.love=love;
    }
    
    /**
     * 看家
     */
    public void lookHome() {
        System.out.println(nickname+"正在给主人看家....");
    }
    /**
     * 重写 :覆盖
     * 1 方法名相同
     * 2 方法参数  返回值类型必须相同
     * 3 访问修饰符不能比父类严格
     * 
     * java特殊 1.7  返回值 可以和父类兼容就可以,必须是引用类型
     */
    
    public String printInfo() {
        System.out.println("狗狗信息:昵称:"+super.nickname+" 颜色:"+super.color+" 品种:"+super.strain+" 亲密度:"+this.love);
        return "haha";
    }
}
8.2 Method rewrite rules

Access to other modifiers return value of the method name (parameter list)

  • 1 in the succession process, method name, parameter list, and return type must be the same as the parent class
  • 2 can not access modifier strict than the parent class
    java 1.7 Special return values can and will be compatible with the parent class, must be a reference type
Overload difference rewriting method and methods 8.3

Overloaded methods: Overload, in the same class, the same method name, parameters of different categories, each other overloads.

Method of rewriting: Override, in the succession process, rewrite the parent class inherited method in a subclass, the method name, parameter list, the return value must be the same access rights can not be stricter than the parent class.

After about 8.4 method of rewriting call:

As long as the override parent class subclass by the subclass object that calls the method must be overridden subclass.

to sum up:

1 方法传参 、返回值

    方法传参采用传值 :  基本类型传递的数据本身,引用类型传递的是地址

        返回值:基本类型返回数据本身,引用类型返回地址。

2 封装 :隐藏类的实现细节,保证程序安全。

    2个步骤

    第一步:私有化成员变量

    第二步:添加get和set方法

3 static关键字

    静态:

    成员变量或方法属于所有对象共有的,不属于每个对象,使用静态。

4 继承: 在原有类的基础上,产生一个新的类,在新的类中可以访问原有类中的非私有成员,并且可以添加一些自己独有的成员,这个过程叫做继承,简单理解一个类继承另外一个类。

   关键字 extends  

   继承符合 is a 关系

   继承特点:1 单继承

            2 继承具有传递性

5 super关键字 :表示当前父类对象的引用

    super.属性  

    super.方法

    super(参数);  调用父类的构造方法

    this和super的区别

6 包: 管理类的,解决类的命名冲突问题。

    域名倒置+项目名

    package  com.qf.day09;   必须是第一句

       导包

        import java.util.*;

7 访问权限修饰符

    public :公开的  

    protected:包含的

    [default]:默认的

    private:私有的 

    类可以用 public  或默认

    成员变量和方法  四个都可以用

8 方法重写:

    重写规则:

    1 在继承中,方法名、参数列表、返回值必须和父类的方法相同

    2 访问权限不能比父类更严格

Dictation

1 什么是类? 什么是对象? 类和对象的关系
2 this关键字的使用?

operation

Design of a rectangle class 1 (the Rectangle), with a length, width attribute, the function to calculate the perimeter, the function of calculating the area

2 Design of a quadrangular prism-based (the Column), a rectangular bottom surface, high property, the surface area calculation, calculate the volume

Interview questions

1 方法重载与方法重写的区别

Guess you like

Origin www.cnblogs.com/Zzzxb/p/11369111.html