zoukankan      html  css  js  c++  java
  • java面向对象------- 封装

    一、封装访问控制符

         本类     同一包下(子类和无关类)  不同包下(子类)   不同包下(无关类)

    Private    y

    默认        y              y

    Protect     y              y                       y

    Public      y              y                      y                   y


    package java面向对象;

    /**
    * 测试封装,private
    */
    public class TestEncapsulation {
    public static void main(String[] args) {
    Human h=new Human();
    //h.name="hahah";对象不能使用类中私有属性

    }
    }

    class Human{
    private String name;
    int age;
    void sayName(){
    System.out.println(name);
    }
    }

    class Boy extends Human{

    void sayhello(){
    // System.out.println(name);//子类无法使用父类的私有属性和方法
    }

    }

    二、封装细节的使用
    package java面向对象;

    /**
    * 测试封装使用细节
    */
    public class Person2Encapsulation {
    private int id;
    private String name;
    private int age;
    private boolean man;
    //外部要使用这些属性时,调用set个get方法
    public void setName(String name){
    this.name=name;
    }
    public void setAge(int age){
    if(age>=18&&age<=130){
    this.age=age;
    }
    else {
    System.out.println("请输入正常年龄");
    }

    }

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

    public static void main(String[] args) {
    Person2Encapsulation p2=new Person2Encapsulation();
    //通过set方法操作类中私有属性,必须符合类中的设置的要求
    p2.setAge(20);
    //通过get方法获取私有类中的属性
    System.out.println(p2.getAge());

    }
    }
  • 相关阅读:
    Solution: Win 10 和 Ubuntu 16.04 LTS双系统, Win 10 不能从grub启动
    在Ubuntu上如何往fcitx里添加输入法
    LaTeX 笔记---Q&A
    Hong Kong Regional Online Preliminary 2016 C. Classrooms
    Codeforces 711E ZS and The Birthday Paradox
    poj 2342 anniversary party
    poj 1088 滑雪
    poj 2479 maximum sum
    poj 2481 cows
    poj 2352 stars
  • 原文地址:https://www.cnblogs.com/zzzao/p/10890410.html
Copyright © 2011-2022 走看看