尚硅谷java零基础教程面向对象(中)239p-273p(2022.3.11)

239 每天一考

1.构造器的作用是创建对象,初始化对象的结构

2.类的属性的赋值,有几种赋值的方法,谈谈赋值的先后顺序

默认初始化--显式初始化--构造器中初始化--对象.方法或对象.属性 给属性赋值

3.this关键字主要用来调用属性,方法,构造器

this理解为当前对象,当前正在创建的对象

4.四种权限修饰

private int age;

private void eat(){}

private double radius;

public void setRadius(double radius){

this.radius=radius;

}

public double getRadius(){

return radius;

}

public double findArea(){

return 3.14*getRadius()*radius;

240 封装性与构造器

面向对象的特征一:封装与隐藏

一:为什么要引入封装性

高内聚:类的内部数据操作细节自己完成,不允许外部干涉;
低耦合:仅对外暴露少量的方法用于使用。

便于外界调用,从而提高系统的可扩展性、可维护性。通俗的说,把该隐藏的隐藏起来,该暴露的暴露出来。这就是封装性的设计思想。

2.问题引入

 当我们创建一个类的对象以后,我们可以通过"对象.属性"的方式,对对象的属性进行赋值。这里,赋值操作要受到属性的数据类型和存储范围的制约。但除此之外,没有其他制约条件。但是,实际问题中,我们往往需要给属性赋值加入额外限制条件。这个条件就不能在属性声明时体现,我们只能通过方法进行条件的添加。比如说,setLegs 同时,我们需要避免用户再使用“对象.属性”的方式对属性进行赋值。则需要将属性声明为私有的(private)  此时,针对于属性就体现了封装性。

 3.封装性思想具体的代码实现

体现一:将类的属性xxx私化(private),同时,提供公共的(public)方法来获取(getxxx)和设置(setxxx)此属性的值

private double radius;

public void setRadius(double radius){

this.radius=radius;

}

public double getRadius(){

return radius;

}

public double findArea(){

return 3.14*getRadius()*radius;

体现二:不对外暴露的私有的方法

体现三:单例模式(将构造器私有化)

体现四:如果不希望类在包外被调用,可以将类设置成缺省的

4.java规定的四种权限修饰符

4.1权限从小到大的顺序为:private <缺省<protected<public

4.2 具体的修饰范围

4.3 权限修饰符可以用来修饰的结构说明

四种权限都可以用来修饰类的内部结构:属性,方法,构造器,内部类修饰类的话,只能使用:缺省,public

1.构造器(或构造方法):Constructor

构造器的作用

   1.创建对象

   2.初始化对象的信息

2.使用说明:

   1.如果没有显示的定义类的构造器的话,则系统默认提供一个空参的构造器。
 * 2.定义构造器的格式:
 *             权限修饰符  类名(形参列表) { }
 * 3.一个类中定义的多个构造器,彼此构成重载。
 * 4.一旦显示的定义了类的构造器之后,系统不再提供默认的空参构造器。
 * 5.一个类中,至少会有一个构造器    
3.举例 

245  项目二功能演示

客户信息管理软件

//Customer为实体对象,用来封装客户信息
public class Customer{
           private String name;
           private char gender;
           private int age;
           private String phone;
           private String email;
           public String getName(){
                  return name;
           }
           public void setName(String name){
                  this.name=name;
           }
           public char getGender(){
                  return gender;
           }
           public void setGender(char gender){
                  this.gender=gender;
           }
           public int getAge(){
                  return age;
           }
           public void setAge(char age){
                  this.age=age;
           }
           public String getPhone(){
                  return phone;
           }
           public void setPhone(String phone){
                  this.phone=phone;
           }
           public String getEmail(){
                  return email;
           } 
           public void setEmail(String email){
                  this.email=email;
           }
           public Customer(){
           }
           public Customer(String name,char gender,int age,String phone,String email){
                   this.name=name;
                   this.gender=gender;
                   this.age=age;
                   this.phone=phone;
                   this.email=email;
           }
}

248 CMUtility工具类的功能介绍

249 Customer类的设计

250 CustomerList类的设计

public class CustomerList{
       private Customer[] customers;//用来保存客户对象的数组、
       private int total=0;//记录已保存客户对象的数量
       //用来初始化customers数组的构造器   totalCustomer:指定数组的长度
       public CustomerList(int totalCustmer){
                customers=new Customer[totalCustomer];
       }
       //将指定的客户添加到数组中  true 添加成功 false 添加失败
       public boolean addCustomer(Customer customer){
            if(total>=customers.length){
                   return false;
            }
            customers[total]=customer;
            total++;
            return true;
       }
       //修改指定索引位置的客户信息  true 修改成功 false 修改失败
       public boolean replaceCustomer(int index,Customer cust){
           if(index<0||index>=total){
                   return false;
           }
           customers[index]=cust;
           return true;
      }
      //删除指定索引位置上的客户  true 删除成功 false 删除失败
       public boolean deleteCustomer(int index){
           if(index<0||index>=total){
                   return false;
           }
           for(int i=index;i<total-1;i++){
               customers[i]=customers[i+1];
           }
           //最后有数据的元素需要置空
           //customers[total-1]=null;
           //total--;
           customers[--total]=null;
           return true;
      }
      //获取所有客户信息
      public Customers[] getAllCustomers(){
          //return customers;
           Customer[] custs=new Customer[total];
           for(int i=0;i<total;i++){
                   cust[i]=customers[i];
           }
           return custs;
      }
      //获取指定索引位置上的客户
      //如果找到了元素,则返回;如果没有找到,则返回null
      public Customer getCustomer(int index){
           if(index<0||index>=total){
                 return null;
           }
           return customers[index];
      }
      //获取存储的客户的数量
      public int getTotal(){
             return total;
     }
         

251  CustomerView整体框架的搭建

public class CustomerView{
  private CustomerList customerList=new CustomerList(10);
  public CustomerView(){
        Customer customer=new Customer("王涛","男","23","13212341234","email");
        customerList.addCustomer(customer);
  //显示客户信息管理软件
  public void enterMainMenu(){
     boolean isFlag=true;
     while(isFlag){
     
     System.out.println("\n--------------客户信息管理软件-----------------");
     System.out.println("                                      1 添加客户");
     System.out.println("                                      2 修改客户");
     System.out.println("                                      3 删除客户");
     System.out.println("                                      4 客户列表");
     System.out.println("                                       5 退 出\n");
     System.out.println("                                    请选择(1-5):");
        char menu=CMUtility.readMenuSelection();
        switch(menu){
        case '1':
             addNewCustomer();
             break;
        case '2':
             modifyCustomer();
             break;
        case '3':
             delectCustomer();
             break;
        case '4':
              listAllCustomers();
              break;
        case '5':
             // System.out.println("退出");
             System.out.print("确认是否退出(Y/N):");
             char isExit=CMUtility.readConfirmSelection();
             if(isExit=='Y'){
                   isFlag=false;
             }
   //  isFlag=false;
     }
  }
  //添加客户的操作
  private void addNewCustomer(){
        //System.out.println("添加客户的操作");
        System.out.println("------------添加客户--------------");
        System.out.print("姓名:");
        String name=CMUtility.readString(10);
        System.out.print("性别:");
        char gender=CMUtility.readChar();
        System.out.print("年龄:");
        int age=CMUtility.readInt();
        System.out.print("电话:");
        String phone=CMUtility.readString(13);
        System.out.print("邮箱:");
        String email=CMUtility.readString(30);
        //将上述数据封装到对象中
        Customer customer=new Customer(name,gender,age,phone,email);
        boolean isSuccess=customerList.addCustomer(customer);
        if(isSuccess){
               System.out.println("----------------添加完成---------------");
        }else{
           System.out.println("---------------客户目录已满,添加失败-----------------");
        }
  }
  //修改客户的操作
  private void modifyCustomer(){
      //System.out.println("修改客户的操作");
      System.out.println("---------------修改客户--------------");
      Customer cust;
      int number;
      for(;;){
      System.out.print("请选择待修改客户编号(-1退出):");
      number=CMUtility.readInt();
      if(number==-1){
             return;
      }
     cust=customerList.getCustomer(number-1);
      if(cust==null){
           System.out.println("无法找到指定客户!");
      }else{//找到了相应编号的客户
          break;
      }
      }
      //修改客户信息
      System.out.print("姓名("+cust.getName()+"):");
      String name=CMUtility.readString(10,cust.getName());
      System.out.print("性别("+cust.getGender()+"):");
      char gender=CMUtility.readChar(cust.getGender());
      System.out.print("年龄("+cust.getAge()+"):");
      int age=CMUtility.readInt(10,cust.getAge());
      System.out.print("电话("+cust.getPhone()+"):");
      String phone=CMUtility.readString(13,cust.getPhone());
      System.out.print("邮箱("+cust.getName()+"):");
      String email=CMUtility.readString(30,cust.getEmail());

      Customer newCust=new Customer(name,gender,age,phone,email);
      boolean isRepalaced=customerList.replaceCustomer(number-1,newCust);
      if(isRepalaced){
          System.out.print("---------------修改完成------------------");
      }else{
          System.out.print("---------------修改失败------------------");
      }
      
  }
  //删除客户的操作
  private void deleteCustomer(){
       //System.out.println("删除客户的操作");
       System.out.println("----------------删除客户---------------");
       int number;
       for(;;){
       System.out.println("请选择待删除客户编号(-1退出):");
       number=CMUtility.readInt();
       if(number==-1){
              return;
       }
       Customer customer=customerList.getCustomer(number-1);
       if(customer==null){
            System.out.println("无法找到该指定客户!");
     }else{
         break;
     }
     //找到了指定的客户
     System.out.print("确认是否删除(Y/N):");
     char isDelete=CMUtility.readConfirmSelection();
     if(isDelete=='Y'){
         boolean deleteSuccess=customerList.deleteCustomer(number-1);
         if(deleteSuccess){
            System.out.println("---------------删除完成------------------");
         }else{
            System.out.println("---------------删除失败-------------------");
         }
     }else{
          return;
     }
       
  }
  //显示客户列表的操作 
  private void listAllCustomers(){
       //System.out.println("显示客户列表的操作");
       System.out.println("------------------客户列表--------------");
       int total=customerList.getTotal();
       if(total==0){
            System.out.println("没有客户记录!");
       }else{
           System.out.println("编号\t姓名\t性别\t年龄\t电话\t邮箱");
           Customer[] custs=customerList.getAllCustomers();
           for(int i=0;i<custs.length;i++){
               System.out.println((i+1)+"\t"+cust.getName()+"\t"+cust.getGender()+"\t"+cust.getAge()+"\t"+cust.getPhone()+"\t"+cust.getEmail());
       }
       System.out.println("------------------客户列表完成-------------");
       
  }
  public static void main(String[] args){
      CustomerView view=new CustomerView();
      view.enterMainMenu();
  }
}

257 项目二总结 

CustomerView为主模块,负责菜单的显示和处理用户操作

对数组的增删改查放到CustomerList

Customer用来封装客户信息

项目简图

CustomerList list=new CustomerList(6);

list.addCustomer(new Customer("Tom",23,'男'));

list.addCustomer(new Customer("Jerry",21,'男'));

258 继承性的理解

public class Person{
      String name;
      int age;
      public Person(){
      }
      public Person(String name,int age){
        this.name=name;
        this.age=age;
      }
      public void eat(){
           System.out.println("吃饭");
      }
      public void sleep(){
           System.out.println("睡觉");
      }
public class Student{
          String name;
          int age;
          String major;
          public Student(){
          }
          public Student(String name,int age,String major){
                this.name=name;
                this.age=age;
                this.major=major;
          }
          public void eat(){
           System.out.println("吃饭");
          }
          public void sleep(){
           System.out.println("睡觉");
          }
          public void study(){
           System.out.println("学习");
          }
      

 

public class ExtendsTest{
         public static void main(String[] args){
              Person p1=new Person();
              p1.age=1;
              p1.eat();
              Student s1=new Student();
              s1.eat();
              s1.sleep();
         } 
 }

259 面向对象的特征之二:继承性

一,继承性的好处

1.减少了代码的冗杂,提高了代码的复用性

2.便于功能的拓展

3.为之后多态性的使用,提供了前提

二,继承性的格式:class A extends B{}

  A:子类,派生类,subclass

  B:父类,超类,基类,superclass

2.1  体现:一旦子类A继承父类B以后,子类A中就获取到了父类B中声明的所有的结构,属性,方法

特别的,父类中声明为private的属性或方法,子类继承父类以后,仍然任务获取了父类中私有的结构,只有因为封装性的理解,使得子类不能直接调用父类的结构而已

2.2 子类继承父类以后,还可以声明自己特有的属性或方法,实现功能的拓展

子类和父类的关系,不同于子集和集合的关系

extends:延展,拓展

260 继承性的再说明

1.一个类可以被多个子类继承

2.Java中类的单继承性:一个类只能有一个父类

3.子父类是相对的概念

4.子类直接继承的父类,称为,直接父类,间接继承的父类称为,间接父类

5.子类继承父类以后,就获取了直接父类以及所有间接父类中声明的属性和方法

261 Object类的理解

1.如果我们没有显式的声明一个类的父类的话,则此类继承于Java.lang.Object类

2.所有的java类(除Java.lang.Object之外)都直接或间接的继承于Java.lang.Object类

3.意味着,所有的java类具有Java.lang.Object类声明的功能

262 每天一考

263 复习项目二

264 复习继承性

一,继承性的好处

1.减少了代码的冗杂,提高了代码的复用性

2.便于功能的拓展

3.为之后多态性的使用,提供了前提

二,继承性的格式

class A extends B{}

  A:子类,派生类,subclass

  B:父类,超类,基类,superclass

三,子类继承父类以后有哪些不同

一旦子类A继承父类B以后,子类A中就获取到了父类B中声明的所有的结构,属性,方法

特别的,父类中声明为private的属性或方法,子类继承父类以后,仍然任务获取了父类中私有的结构,只有因为封装性的理解,使得子类不能直接调用父类的结构而已

2.2 子类继承父类以后,还可以声明自己特有的属性或方法,实现功能的拓展

子类和父类的关系,不同于子集和集合的关系

extends:延展,拓展

四.java中继承性的说明

1.一个类可以被多个子类继承

2.Java中类的单继承性:一个类只能有一个父类

3.子父类是相对的概念

4.子类直接继承的父类,称为,直接父类,间接继承的父类称为,间接父类

5.子类继承父类以后,就获取了直接父类以及所有间接父类中声明的属性和方法

五,java.lang.Object类的理解 

1.如果我们没有显式的声明一个类的父类的话,则此类继承于Java.lang.Object类

2.所有的java类(除Java.lang.Object之外)都直接或间接的继承于Java.lang.Object类

3.意味着,所有的java类具有Java.lang.Object类声明的功能

 265 继承性练习1:基本操作

 

public class ManKind{
     private int sex;
     private int salary;
     public Mankind(){
     }
     public Mankind(int sex,int salary){
             this.sex=sex;
             this.salary=salary;
     }
     public void manOrWoman(){
          if(sex==1){
              System.out.println("man");
          }else if(sex==0){
              System.out.println("woman");
          }
     }
     public void employeed(){
            if(salary==0){
                  System.out.println("no job");
            }else{
                  System.out.println("job");
            }
     }
     public int getSex(){
           return sex;
     }
     public void setSex(int sex){
           this.sex=sex;
     }
     public int getSalary(){
           return salary;
     }
     public void getSalary(int salary){
           this.salary=salary;
     }
}
public class Kids extends Mankind{
     private int yearsOld;
     public Kids(int yearsOld){
           this.yearsOld=yearsOld;                                                                                               
     }
     public void printAge(){
       System.out.println("I am"+yearsOld+"years old.");
       }
     public int getYearsOld(){
          return yearsOld;
       }
     public void setYearsOld(int yearsOld){
          this.yearsOld=yearsOld;
      }
}
public class KidsTest{
      public static void main(String[] args){
             Kids someKid=new Kids(12);
             someKid.printAge();
             someKid.setSalary(0);
             someKid.setSex(1);
             someKid.employeed();
             someKid.manOrWoman();
}
}

266 继承性练习2:基本操作

 

public class Circle{
     private double radius;
     public Circle(){
            radius=1.0;
     }
     public double getRadius(){
            return radius;
     }
     public void setRadius(double radius){
            this.radius=radius;
     }
     //返回圆的面积
     public double findArea(){
           return Math.PI*radius*radius;
     }
public class Cylinder extends Circle{
    private double length;
    public Cylinder(){
       length=1.0;
    }
    public double getLength(){
        return length;
    }
    public void setLength(double length){
        this.length=length;
    }
    //返回圆柱的体积
    public double findVolume(){
           return Math.PI*getRadius()*getRadius()*getLength();
    }
}
public class CylinderTest{
    public static void main(String[] args){
        Cylinder cy=new Cylinder();
        cy.setRadius(2.1);
        cy.setLength(3.4);
        double volume=cy.findVolume();
        System.out.println("圆柱的体积为:"+volume);
        double area=cy.findArea();
        System.out.println("底面圆的面积为:"+area);
}
}

270 方法重写的理解

 

public class Person{
          String name;
          int age;
          public Person(){
          }
          public Person(String name,int age){
               this.name=name;
               this.age=age;
          }
          public void eat(){
             System.out.println("吃饭");
          }
          public void walk(int distance){
             System.out.println("走路,走的距离是:"+distance+"公里");
          }
}
public class Student extends Person{
     String major;
     public Student(){
     }
     public Student(String major){
          this.major=major;
     }
     public void study(){
           System.out.println("学习的专业是:"+major);
    }
    public void eat(){
             System.out.println("学生应该多吃点有营养的东西");
          }
}
public class PersonTest{
      public static void main(String[] args){
              Student s=new Student();
              Student s=new Student("计算机科学与技术");
              s.eat();
              s.walk(10);
              s.study();
}
}

方法的重写(override/overwrite) 

 1.重写:子类继承父类以后,可以对父类中同名同参数的方法,进行覆盖操作

2.应用:重写以后,当创建子类对象以后,通过子类对象调用子父类中的同名同参数的方法时,实际执行的是子类重写父类的方法

面试题:区分方法的重载与重写

271 方法重写的细节

重写的规定

   方法的声明:权限修饰符  返回值类型 方法名(形参列表)throws 异常的类型{

                                                      //方法体

                                              }

   约定俗称:子类中的叫重写的方法,父类中的叫做被重写的方法

1.子类重写的方法的方法名和形参列表与父类被重写的方法的方法名和形参列表相同

2.子类重写的方法的权限修饰符不小于父类被重写的方法的权限修饰符

     特殊情况:子类不能重写父类中声明为private权限的方法

3.返回值类型

   父类被重写的方法的返回值类型是void,则子类重写的方法的返回值类型只能是void

  父类被重写的方法的返回值类型是A类型,则子类重写的方法的返回值类型可以是A类或A类的子类

     父类被重写的方法的返回值类型是基本数据类型(比如:double),则子类重写的方法的返回值类型必须是相同的基本数据类型(必须也是double)

4.子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型

子类和父类中的同名同参数方法要么都声明为非static的(考虑重写),要么都声明为static的(不是重写)

 272  方法重写的练习

 1.如果现在父类的一个方法定义成private访问权限,在子类中将此方法声明为default访问权限,那么这样还叫重写吗?(NO)

2.2.修改练习1.2中定义的类Kids,在Kids中重新定义employeed()方法,

* 覆盖父类ManKind中定义的employeed()方法,

* 输出“Kids should study and no job.”

273 测试四种不同的权限修饰

//体会四种不同的权限修饰
public class Order{
        private int orderPrivate;
        int orderDefault;
        protected int orderProtected;
        public int orderPublic;
        private void methodPrivate(){
            orderPrivate = 1;
		    orderDefault = 2;
		    orderProtected = 3;
		    orderPublic = 4;
        }
        void methodDefault(){
            orderPrivate = 1;
		    orderDefault = 2;
		    orderProtected = 3;
		    orderPublic = 4;
        }
        protected void methodProtected(){
            orderPrivate = 1;
		    orderDefault = 2;
		    orderProtected = 3;
		    orderPublic = 4;
        }
        public void methodPublic(){
            orderPrivate = 1;
		    orderDefault = 2;
		    orderProtected = 3;
		    orderPublic = 4;
        }
}
public class OrderTest{
    public static void main(String[] args){
       Order order=new Order();
       order.orderDefault=1;
       order.orderProtected=2;
       order.orderPublic=3;
       order.methodDefault();
       order.methodProtected();
       order.methodPublic();
       //同一个包中,不可以调用Order类中私有的属性或方法
       
public class SubOrder extends Order{
         public void method(){
             orderProtected=1;
             orderPublic=2;
             methodProtected();
             methodPublic();
             //在不同包的子类下,不能调用Order类中声明为private和缺省权限的属性和方法
public class OrderTest{
   public static void main(String[] args){
           Order order=new Order();
           order.orderPublic=1;
           order.methodPublic();
           //不同包下的普通类(非子类)要使用Order类,不可以调用声明为private,缺省,protected权限的属性,方法
}

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

京与旧铺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值