标签:注意事项 信息 name 对象数组 exti 个数 ret bsp protected
一.访问修饰符
1.public:公共的,所有在该项目中都可见
2.protected:受保护的,同包,以及子类不同包可见
3.默认:就是不写修饰符。同包
4.private:私有,只在同类中
二.封装
1.定义:将信息和实现的细节封装到类中,对外只提供方法的访问
2.作用:隐藏实现细节,可以简化工作流程。隐藏信息,可以防止数据被随意修改
3.封装步骤:
a。将类中的属性访问修饰符改为私有的
b。写一对公共的方法来操作私有的属性:set/get方法
c。在set或者get方法中加入业务限制来修改属性
三.static关键字
1.定义:静态关键字,可以修饰属性,方法和代码块。
2.作用:是在类被加载时,被静态修饰的东西都被加载就绪。
静态属性和静态方法可以通过类名直接访问
3.注意事项:静态方法不能访问外部的非静态成员,静态方法中不能使用this关键字
4.使用场景:常用的工具类方法可以写成静态。
四.方法的重载
1.定义:是在同一个类中,出现同名方法,但参数列表必须不同(个数,类型,顺序)
2.特点:
必须在同一个类中
参数列表必须不同
与访问修饰符和返回值无关
五.例子
/*
* 1.编写一个人类,封装他的性别属性,要求性别只能赋值为男或女,其他不接受。
编写测试类,创建该对象给他性别属性赋值,打印输出其性别
*/
package com.class1103;
import java.util.Scanner;
public class Class01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Man m=new Man();
System.out.println("请输入性别");
m.setSex(sc.next());
System.out.println("性别是"+m.getSex());
System.out.println("请输入年龄");
m.setAge(sc.nextInt());
System.out.println("年龄是"+m.getAge());
}
}
class Man{
private String sex;
private int age;
public void setSex(String sex)
{
if(sex.equals("男")||sex.equals("女"))
{
this.sex=sex;
}else{
System.out.println("是人妖");
}
}
public String getSex()
{
return sex;
}
public void setAge(int age)
{
if(age>=1&&age<=150)
{
this.age=age;
}else{
System.out.println("是千年老人妖");
}
}
public int getAge()
{
return age;
}
}
/*
* 对象数组
*/
package com.class1103;
public class Class02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student[] stu=new Student[20];
stu[0]=new Student("关羽",58,"男");
stu[1]=new Student("张飞",55,"男");
stu[2]=new Student("赵云",50,"男");
stu[3]=new Student("黄忠",67,"男");
stu[4]=new Student("马超",47,"男");
for(int i=0;i<5;i++)
{
System.out.print(stu[i].name+" ");
System.out.print(stu[i].age+" ");
System.out.print(stu[i].sex+" ");
System.out.println();
}
}
}
class Student{
String name;
int age;
String sex;
public Student(String name,int age,String sex)
{
this.name=name;
this.age=age;
this.sex=sex;
}
}
package com.demo1103;
/**
* 实现信息的封装
* @author allen
*
*/
public class Demo1 {
private double balance;
public void setBalance(double balance){
if(balance<0){
System.out.println("骗子死开");
return;
}else{
System.out.println("你就是我亲爹啊");
this.balance += balance;
}
}
public double getBalance(){
return balance;
}
public static void main(String[] args) {
Demo1 d = new Demo1();
d.setBalance(-1000);
System.out.println("您当前的余额是:"+d.getBalance());
}
}
package com.demo1103;
import java.util.Arrays;
/**
* 静态关键字和方法重载案例
*
*/
public class Test {
String name;
static int age;
static{
System.out.println("我是静态块");
}
public void test(int a,String b){
System.out.println("你好");
}
//重载
private int test(){
return 1;
}
public static void hello(){
age = 1;
System.out.println("hello");
}
public static void main(String[] args) {
int a = 1;
a = 1;
Test.hello();
}
}
标签:注意事项 信息 name 对象数组 exti 个数 ret bsp protected
原文地址:https://www.cnblogs.com/wlxslsb/p/10353998.html