Java learning Day12-encapsulation, inheritance, polymorphism

Three characteristics of object-oriented languages

Encapsulation

​ Packaging wraps up the implementation details and provides method access to the outside world

​ Hide some information or member methods in the class, which cannot be directly accessed from the outside, and provide some special method operations to the outside;

​ hide (access modifier)

public class Person {
    
    

    /**
    通过访问修饰符来隐藏类中的信息
     */
    private String name;
    private int age;
  
   /* public   Person(String n , int a){k
        name = n;
        age = a;
    }*/

    /**
    *为私有属性提供专门的方法来进行访问
     * this 现实的表示当前正在访问的对象
     */
    public void setName(String name) {
    
    
        if (name.length() < 5) {
    
    
            this.name = name;//对象p访问时,this表示的是p对象
            eat();
        }else{
    
    
            this.name="肖恩";
            this.eat();//本类中访问私有权限的方法
        }
    }
    public String getName(){
    
    
        return name;
    }

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

    /*
    私有权限的方法,可以在本类中访问
     */
    private void eat() {
    
    
        System.out.print("干饭王:");
    }
}

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

        /*Person p = new Person("jim",20);*/
        /*Person p1 = new Person("jack",28);*/

        Person p = new Person();
               p.setName("崔");
               p.setAge(21);
        System.out.println(p.getName()+p.getAge());


        Person p1 = new Person();
               p1.setName("瑞");
               p1.setAge(22);
        System.out.println(p1.getName()+p1.getAge());
    }
}

this keyword

The this keyword represents objects of its own class

Note: this keyword must be placed in a non-static method

public class Demo{
    
    
	private int a;
			
	public Demo(int a){
    
    
	    this.a = a;
	}
			
	public int getA(){
    
    
		return a;
	}
			
	public void setA(int a){
    
    
		this.a = a;
	}
}

inherit

  1. The parent class is inherited by the child class
  2. Subclasses can have some of the functions of the parent class
  3. Inheritance is a design idea of ​​object-oriented language
  4. Can improve code reusability and code scalability

for example

Humans: Shared name attributes

​ Student category: inherited human attributes: student number

​ Primary school students: inherit the student class

​ Middle school students: inherit the student class

​ College students: inherit the student class

​ Worker class: inheriting human's own attributes: job number and type of work

What kind of relationship can use inheritance?
​ Things of the same type (is a relationship)

Class A extends Object{}
Class B extends Class A{}
Class C extends Class B{}

Create a parent class (People)

package com.ff.javaopp.Day004;
/*
    primarySchool类继承People
    PrimarySchool是People的子类(派生类)
    父类(基类)
    把人类相关的一些公有属性,行为,定义在people类中
    extends关键字

    当一个类没有显示的继承一类,那么这个类默认继承object
    object是java所有类的基类 称超类
 */
public class People {
    
    

    private String name ;
    private int age;

    public People(){
    
    
        System.out.println("人类中的无参的构造方法");
    }

    public People(String name){
    
    
        this.name=name;
        System.out.println("人类中的有参的构造方法");
    }

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

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


    public void eat(){
    
    
        System.out.println(name+"干饭人,干饭魂,干饭都是人上人");
    }
}

Create a subclass (PrimarySchool)

public class PrimarySchool extends People {
    
    

    private String clas;

    public PrimarySchool(){
    
    
        super("小红");
        System.out.println("小学生中的无参构造方法");
    }
    public void setClass(String clas){
    
    
        this.clas=clas;
    }
    public String getClas(){
    
    
        return clas;
    }


    public void play(){
    
    
        System.out.println("过家家");
    }

}

Create a subclass (MiddleSchool)

public class MiddleSchool extends People{
    
    
    private String grade;
    public void study(){
    
    
        System.out.println("学习人,学习魂,学习都是人上人");
    }

    public void setGrade(String grade){
    
    
        this.grade=grade;
    }
    public String getGrade(){
    
    
        return grade;
    }

}

Create a test class (PeopleTset)

package com.ff.javaopp.Day004;

public class PeopleTset  {
    
    
    public static void main(String[] args) {
    
    
        PrimarySchool p = new PrimarySchool();
        p.setName("瑞瑞");//父类
        p.setAge(21);//父类
        p.setClass("学前班");//小学生自己的属性
        System.out.println(p.getName()+p.getAge());//父类
        System.out.println(p.getClas());//小学生自己的属性
        p.eat();//父类
        p.play();//小学生自己的方法

        MiddleSchool M = new MiddleSchool();
        M.setName("荣荣");//父类
        M.setAge(22);//父类
        M.setGrade("高中生");//高中生自己的属性
        System.out.println(M.getName()+M.getAge());//父类
        System.out.println(M.getGrade());//高中生自己的属性
        M.study();//高中生自己的属性
        M.eat();//父类

        p.hashCode();//调用object类中的方法
        /*
        子类继承了父类后,可以拥有父类中私有属性,方法
         */
    }
}

When creating a subclass object, the parent class construction method will be called first to create the parent class object

public class Test {
    
    
    /*
    继承中的构造方法
    在创建一个子类对象时,同时也会创建父类对象
     */
    public static void main(String[] args) {
    
    
        XiaoMing xm= new XiaoMing();
        xm.eat();
    }
}

super means the parent class

The super keyword represents the reference of the parent class, the main purpose in the program

To call the construction method of the parent class in the subclass construction method, you need to pay attention: the super statement can only appear in the first line of the subclass construction method body.
Use "super. member variable name" to refer to the parent class member variable.
Use "super. method name (parameter list)" to access the method of the parent class.
The difference with this, this usually refers to the current object, and super usually refers to the parent class.

Create a subclass (XiaoMing) of Primary School (PrimarySchool)

public class XiaoMing extends PrimarySchool{
    
    

    /*
    在调用子类方法时,会先调用父类的构造方法
     */
    public XiaoMing(){
    
    
        //super(); 构造方法第一行默认使用super();调用父类默认无参的构造方法
        super();//需要显示调用,必须放在构造方法的第一行
        System.out.println("小学生小明中无参的构造方法");
    }
 }

Method rewriting

Why use method rewriting?

It can be overridden when the implementation of the parent class cannot meet the functions of the subclass

public class XiaoMing extends PrimarySchool{
    
    
    /*
    方法的重写:当子类中的实现步骤与父类中的实现方式不同时,
    可以在子类中将父类中的方法重写
            必须与父类的方法结构相同(返回值,参数)
            子类重写后的方法的权限范围要大于等于父类方法的访问权限

            super表示当前类的父类对象
            在子类中可以通过super访问父类中成员

            @Override 注解  标签
            表明该方法是从父类中重写过来了的
     */
    @Override
    public void eat(){
    
    
        System.out.println("小明喜欢吃面面");
        super.eat();//调用父类成员
    }

    public void Question(){
    
    
        System.out.println("小学生小明喜欢问问题");
    }
}

Understand relationships and dependencies

Create a Mobile class

public class Mobile {
    
    
    private  String num;
    public String getNum() {
    
    
        return num;
    }
    public void setNum(String num) {
    
    
        this.num = num;
    }
}

Association relationship: has-a relationship XXX has XXX
dependency relationship: use-a relationship uses another class in a certain class

public class Person {
    
    
    private Mobile mobile;//单向关联 一对一关联
    private Mobile[] mobiles;//单项关联  一对多关联

    /*
    依赖关系,Person中的某个方法中使用到另一个类
     */
    public void callPeople(MiddleSchool middleSchool){
    
    
        middleSchool.study();
        middleSchool.setAge(25);//传递过来的是引用类型,会改变原来的值
    }
   }

Abstract class abstract

  1. If a class does not contain enough information to describe a specific object, such a class is an abstract class
  2. Abstract class is also a class
  3. Abstract method: modified by the abstract keyword, there is no method body, just as the definition of the function

Features abstract class:
can not create an object because it contains an abstract method
contain constructors, when you create a subclass of objects, you can create the parent object Introduction

Create the Animal class

/*
    被abstract修饰的类就是抽象类
    抽象类中不一定有抽象方法
    有抽象方法,那么这个类必定是抽象类
 */
public abstract class Animal {
    
    
    String name;
    /*
      在顶层类中,方法的实现与子类大多不相同,那么在顶层类中可以将方发声明为抽象方法
      被abstract修饰,没有方法体
      只作为方法的定义
    */
    public abstract void eat();
    public abstract void sleep();

    public void play(){
    
    
        System.out.println("Animal Play");
    }
}

Create a subclass Dog class

/*
    抽象类就是作为定义,让其他类继承

    一个类继承抽象类:
        要么将子类声明为抽象类
        要么重写抽象类中所有的抽象方法
 */
public class  Dog  extends Animal{
    
    

    @Override
    public void eat() {
    
    
        System.out.println("狗子吃");
    }

    @Override
    public void sleep() {
    
    
        System.out.println("狗子睡");
    }
}

Create a subclass Cat class

package com.ff.javaopp.Day004.abstractDemo;

public class Cat extends Animal{
    
    
    @Override
    public void eat() {
    
    
        System.out.println("猫吃鱼");
    }

    @Override
    public void sleep() {
    
    
        System.out.println("猫睡觉");
    }
}

Create test class

package com.ff.javaopp.Day004.abstractDemo;

public class Test {
    
    
    public static void main(String[] args) {
    
    
       Dog d = new Dog();
        d.eat();
        d.sleep();
        d.play();    
}

Polymorphism

Same kind of things, showing different states at different moments

Conditions for polymorphism:

  1. There must be inheritance
  2. There must be a way to rewrite
  3. The reference of the parent class points to the object of the child class

Don't use polymorphism

public class Test {
    
    
    public static void main(String[] args) {
    
    
     /*   Dog d = new Dog();
        d.eat();
        d.sleep();
        d.play();*/
        //Dog d = new Dog();不是多态
        Dog dog = new Dog();
        Cat cat = new Cat();
        Test t = new Test();
        t.feedCat(cat);
        t.feedDog(dog);
    }

    public void feedDog(Dog dog) {
    
    
        dog.eat();
        dog.sleep();
    }

    public void feedCat(Cat cat) {
    
    
        cat.eat();
        cat.sleep();
    }
}

The code is too redundant

Use polymorphism

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

        Animal dog = new Dog();
                //dog.eat();编译期间看左边,运行期间看右边
        Animal cat = new Cat();
        Test1 t = new Test1();
        t.feedAnimal(cat);
        t.feedAnimal(dog);
    }

    public void feedAnimal(Animal animal) {
    
    
        animal.eat();//
        animal.sleep();
    }
}

operation result:

猫吃鱼
猫睡觉
狗子吃
狗子睡

Guess you like

Origin blog.csdn.net/XiaoFanMi/article/details/110328253
Recommended