首页 > 编程语言 >封装,继承(super,this,方法重写),多态--JAVA

封装,继承(super,this,方法重写),多态--JAVA

时间:2022-11-16 20:11:48浏览次数:41  
标签:JAVA String -- void 多态 System println public name

一、封装

封装:就是把抽象出的数据【属性】和对数据的操作【方法】封装在一起,数据被保护在内部,程序的其他部分只有通过被授权的操作才能对数据进行操作

 

 

public class var {

public static void main(String[] args) {
Person person = new Person();
person.setSalary(550);
person.setAge(20);
person.setName("jacky");
System.out.println(person.info());




}
}


//年龄在1-120;年龄,工资不能直接查看;name的长度在2-6之间
class Person{
public String name;
private int age;
private double salary;
//快捷键alt+inset

public int getAge() {
return age;
}

public void setAge(int age) {
if (age<=100 && age>=1){
this.age = age;
}else{
System.out.println("设置的年龄范围错误,设置默认年龄18");
this.age =18;//给一个默认的值
}
}

public double getSalary() {
//可以增加权限禁止查看
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}
public String getName() {
return name;
}

public void setName(String name) {
if (name.length()>=2 && name.length()<=6) {
this.name = name;
}else { System.out.println("设置的年龄范围错误,设置默认名字steve");
this.name ="steve";//给一个默认的名字
}
}
public String info() {
return "name=" + name + "age = " + age + "salary = " + salary;
}

}

//创建程序,其中定义两个类:Account和AccountTest类体会JAVA的封装性
//1.Account类要求具有属性:姓名(长度为2,3,4位),余额(必须>20),
//密码(必须是六位),如果不满足则给出提示信息并给出默认值
//2.通过setXxx的方法给Account的属性赋值
//3.在AccountTest中测试

在一个包下创建两个类

 

 

package example;

public class Account {
//为了封装,将3个属性设置为private
private String name;
private double balance;
private String pwd;
//快捷键
public String getName() {
return name;
}

//提供两个构造器
//无参构造器
public Account() {

}
//有参构造器
public Account(String name, double balance, String pwd) {
this.setName(name);
this.setBalance(balance);
this.setPwd(pwd);

}

public void setName(String name) {
if (name.length()>=2 && name.length()<=4 ){
this.name = name;
}else{
System.out.println("输入错误,默认值为name");
this.name = "name";
}
}

public double getBalance() {
return balance;
}

public void setBalance(double balance) {
if (balance>20){
this.balance = balance;
}else {
System.out.println("输入错误,默认值为0");
this.balance = 0;

}
}

public String getPwd() {
return pwd;
}

public void setPwd(String pwd) {
if (pwd.length()==6){
this.pwd = pwd;
}else{
System.out.println("输入错误,默认值为0");
this.pwd = "000000";
}
}
public void showinfo(){
System.out.println("name="+getName()+" "+"banlance="+getBalance()+" "+"pwd="+getPwd());
}

}

package example;


public class AccountTest {
public static void main(String[] args) {
Account account = new Account();
account.setName("jacky");
account.setBalance(20);
account.setPwd("123456");
account.showinfo();
}
}

 

 

 

二、继承

 

 

 

 

 

 

 细节:

 

 

 

 

 

 

 

2. 子类默认调用父类的无参构造器

 

 

 

 

 

 

 

//讲解继承的本质
//加载son时先加载GrandPa的父类object
//再加载GrandPa,再加载father,最后是son

public class ExtendsTheory {
public static void main(String[] args){
Son son = new Son();//问执行完这个代码后内存发生了什么改变
// (1)先看子类是否有这个属性,若有并且可以访问就输出子类的
// (2)如果子类没有这个属性,就向上查找父类,若父类有并且可以访问就返回
// (3)如果父类没有就按照(2)的规则,继续找上级父类,知道object
System.out.println(son.name);//输出大头儿子
System.out.println(son.age);//输出39
System.out.println(son.hobby);//输出旅游
}

}

class GrandPa{ //父类Father的父类
String name = "大头爷爷";
String hobby = "旅游";
}

class Father extends GrandPa{//父类Father,继承父类的父类Grandpa
String name = "小头爸爸";
int age = 39;
}

class Son extends Father{//子类son,继承父类Father
String name = "大头儿子";
int age = 39;
}


//private访问方法
public class ExtendsTheory {
public static void main(String[] args){
Son son = new Son();//问执行完这个代码后内存发生了什么改变
// (1)先看子类是否有这个属性,若有并且可以访问就输出子类的
// (2)如果子类没有这个属性,就向上查找父类,若父类有并且可以访问就返回
// (3)如果父类没有就按照(2)的规则,继续找上级父类,知道object
System.out.println(son.name);//输出大头儿子
//System.out.println(son.age);//输出39
System.out.println(son.getAge());
System.out.println(son.hobby);//输出旅游
}

}

class GrandPa{ //父类Father的父类
String name = "大头爷爷";
String hobby = "旅游";
}

class Father extends GrandPa{//父类Father,继承父类的父类Grandpa
String name = "小头爸爸";
private int age = 39;

public int getAge() {
return age;
}
}

class Son extends Father{//子类son,继承父类Father
String name = "大头儿子";
//int age = 39;
}

 

public class ExtendsTheory {
public static void main(String[] args){
C c = new C();
// 我是A类
// haha我是B类的有参构造器
// 我是C类的有参构造器
// 我是C类的无参构造器
}

}

class A{//A的父类时object
public A(){
System.out.println("我是A类");
}
}

class B extends A{//父类B继承父类的父类A
public B(){
System.out.println("我是B类的无参构造器");
}
public B(String name){
//默认super();
System.out.println(name+"我是B类的有参构造器");
}
}

class C extends B{//子类C继承父类B
public C(){
this("hello");
System.out.println("我是C类的无参构造器");
}
public C(String name){
super("haha");
System.out.println("我是C类的有参构造器");
}
}
//解析:1.this("hello") 2.super("haha") 3.System.out.println(haha+"我是B类的有参构造器");4.输出第一个:我是A类
5.输出第二个:haha我是B类的有参构造器 6.输出第三个:我是C类的有参构造器 7.输出第四个:我是C类的无参构造器

 

//编写Computer类,包含CPU、内存、硬盘等属性,getDetails方法用于返回Computer的详细信息
//编写PC子类,继承Computer类,添加特有属性【品牌brand】
//编写NotePad子类,继承Computer类,添加特有属性【color】
//编写Test类,在main方法中创建PC和NotePad对象,分别给对象中特有的属性赋值
//以及从Computer类继承的属性赋值,并使用方法并打印输出信息

主类:

public class Computer {
private String cpu;
private int memory;
private int disk;

public Computer(String cpu, int memory, int disk) {
this.cpu = cpu;
this.memory = memory;
this.disk = disk;
}
public String getDetails() {
return "cpu=" + cpu + " memory" + memory + " disk" + disk;
}

public String getCpu() {
return cpu;
}

public void setCpu(String cpu) {
this.cpu = cpu;
}

public int getMemory() {
return memory;
}

public void setMemory(int memory) {
this.memory = memory;
}

public int getDisk() {
return disk;
}

public void setDisk(int disk) {
this.disk = disk;
}
}

//子类PC:
public class PC extends Computer{
private String brand;

public PC(String cpu, int memory, int disk, String brand) {
super(cpu, memory, disk);
this.brand = brand;
}

public String getBrand() {
return brand;
}

public void setBrand(String brand) {
this.brand = brand;
}
public void printInfo() {
System.out.println("PC信息如下");
System.out.println(getDetails() + " brand" + brand);
}
}

super关键字用法

 


 

 

 

 

public class A {
public int n1=100;
protected int n2 =200;
int n3 =300;
private int n4 =400;
public A(){}
public A(String name){}
public A(String name,int age){}

public void cal() {
System.out.println("A类的cal()方法");
}
public void test100(){

}
protected void test200(){

}
void test300(){

}
private void test400(){

}
}

public class B extends A{
public int n1 = 888;
//访问父类的属性,但不能访问父类的private属性
public void hi(){
System.out.println(super.n1+super.n2+super.n3);
}
public void sum() {
System.out.println("B类的sum()");
//希望调用父类A的cal方法
//这时因为子类B没有cal方法,因此可以使用下面3种方式
//顺序:现在子类中找,如果没有再去父类
//cal();
//this.cal();//等价cal
super.cal();//顺序:直接查找父类,其他的规则一样
//演示访问属性的规则
//System.out.println(n1);//规则:先找本类调用,没有再找父类
//System.out.println(this.n1);//同上
//System.out.println(super.n1);//直接找父类

}
//访问父类的方法,不能访问父类的private方法
public void ok() {
super.test100();
super.test200();
super.test300();
}
//访问父类的构造器:super(参数列表);只能放在构造器的第一句,只能出现一句
public B() {
//super();
//super("jack",10);
//super("jack");
}
}



 

 


 

 方法重写

 

 

 

public class Animal {
public void cry(){
System.out.println("动物叫唤");
}
}

public class Dog extends Animal{
public void cry(){
System.out.println("小狗汪汪叫");
}
}

 

//1.因为dog是animal子类
//2.dog的cry方法和animal的cry定义形式一样(名称、返回类型、参数)
//3.这时就说dog的cry方法重写了父类的animal的cry方法

Dog dog = new Dog();
dog.cry();//ctrl+b,调用子类

 

 

 

 

public class Person {
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age = age;
}
public String say() {
return "name=" + name + "age=" + age;
}
public String getName(){
return name;
}

public void setName(String name){
this.name=name;
}
public int getAge(){
return age;
}

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

public class Student extends Person{
private int id;
private double score;
public Student(String name,int age,int id,double score){
super(name,age);
this.id=id;
this.score=score;
}
public String say() {
return super.say() + "id=" + id + "score=" + score;
}
public int getId(){
return id;
}

public void setId(int id){
this.id=id;
}
public double getScore(){
return score;
}

public void setScore(double score){
this.score=score;
}

}


三、多态

 

 

 

 

 

public class Animal {
public void cry(){
System.out.println("Animal cry() 动物在叫");
}
}

public class Cat extends Animal{
public void cry(){
System.out.println("cat cry() 小猫在叫");
}

}

public class Dog extends Animal{
public void cry(){
System.out.println("dog cry() 小狗在叫");
}
}
public class polyobject {
public static void main(String[] args) {
//animal编译类型是Animal,运行类型是Dog
Animal animal = new Dog();
animal.cry();//输出的是dog
animal = new Cat();
animal.cry();
}
}
//////////////////
//    public void feed(Dog dog,Bone bone) {
// System.out.println("主人" + name + "给" + dog.getName() + "吃" + bone.getName());
// }
// public void feed(Cat cat,Fish fish) {
// System.out.println("主人" + name + "给" + cat.getName() + "吃" + fish.getName());
// }

public void feed(Animals animal,Food food) {
System.out.println("主人" + name + "给" + animal.getName() + "吃" + food.getName());
}

public class Poly01 {
public static void main(String[] args) {
Master tom = new Master("tom");
Dog dog = new Dog("大黄");
Bone bone = new Bone("大棒骨");
tom.feed(dog,bone);
Master lily = new Master("lily");
Cat cat = new Cat("臭卷宝");
Fish fish = new Fish("黄花鱼");
lily.feed(cat,fish);
}
}

 

 向上转型

public class Animal {
String name="动物";
int age = 10;
public void sleep(){
System.out.println("睡");
}
public void run(){
System.out.println("跑");
}
public void eat(){
System.out.println("吃");
}
public void show(){
System.out.println("你好");
}
}

public class Cat extends Animal{
public void eat(){//方法重写
System.out.println("猫吃鱼");
}

public void catchMouse(){//特有的方法
System.out.println("猫抓老鼠");
}
}

public class polydetail {
public static void main(String[] args){
//向上转型:父类的引用指向了子类的对象
//语法:父类类型引用名 = new 子类类型();
Animal animal = new Cat();
//Object obj = new Cat();
//可以调用父类的所有成员(要遵守访问权限,private不能调用),但是不能调用子类特有的成员
//animal.catchmouse错误,因为再编译阶段,能调用哪些成员(属性+方法)是由编译类型决定的
//最终运行效果看子类的具体实现,即调用方法时,按照从子类开始查找方法
//,然后调用,规则和前面的一致
animal.eat();
animal.run();


}
}

 

 向下转型

public class polydetail {
public static void main(String[] args){
//向上转型:父类的引用指向了子类的对象
//语法:父类类型引用名 = new 子类类型();
Animal animal = new Cat();
//Object obj = new Cat();
//可以调用父类的所有成员(要遵守访问权限,private不能调用),但是不能调用子类特有的成员
//animal.catchmouse错误,因为再编译阶段,能调用哪些成员(属性+方法)是由编译类型决定的
//最终运行效果看子类的具体实现,即调用方法时,按照从子类开始查找方法
//,然后调用,规则和前面的一致
animal.eat();
animal.run();
//多态的向下转型
//怎么调用cat的catchmouse方法
//语法:子类类型 引用名=(子类类型)父类引用
Cat cat = (Cat) animal;
cat.catchMouse();

}
}

 

 

public class PolyDetail03{
public static void main(String[] args){
BB bb = new BB();
//instanceof比较操作符,用于判断对象的类型是否为XX类型或XX类型的子类型
System.out.println(bb instanceof BB);//true
System.out.println(bb instanceof AA);//true
AA aa = new BB();
System.out.println(aa instanceof AA);//true
System.out.println(aa instanceof BB);//true
Objcet obj = new Object();
System.out.println(obj instanceof AA);//false,obj不是AA的同类或子类

}
}

class AA{}//父类
class BB extends AA{}//子类


案例
public class PolyExericse01{
public static void main(String[] args){
double d =13.4;//ok
long l = (long)d;//ok
System.out.println(l);//13
int in =5;//ok
boolean b =(boolean)in;//false
Object obj = "Hello";//ok,String转成object,向上转型(多态)
String obStr=(String)obj;//ok.向下转型
System.out.println(objStr);//hello

Object objPri = new Interger(5);//ok,向上转型
Stringg str = (String)objPri;//false,指向Integer的父类引用转成String
Integer str1 = (Integer)objPri;//ok,向下转型
}
}

属性看编译,方法看运行

 


 动态绑定机制

动态绑定机制:
1、当调用对象方法的时候,该方法会和对象的内存地址/运行类型绑定
2、当调用对象属性时,没有动态绑定机制,哪里声明哪里使用

public class DuoTai {
public static void main(String []args){
A a =new B();
System.out.println(a.sum());//40->30
System.out.println(a.sum1());//30->20
}
}

class A {
public int i =10;
public int sum(){
return geti()+10;
}
public int sum1(){
return i +10;
}
public int geti(){
return i ;
}
}

class B extends A{
public int i =20;
// public int sum(){
// return i+20;
// }
public int geti(){
return i;
}
// public int sum1(){
// return i+10;
// }
}

多态数组

 


 

public class Person {
private String name;
private int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
public String say(){
return name + age;
}
}

public class Student extends Person{
private double score;

public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}

public double getScore() {
return score;
}

public void setScore(double score) {
this.score = score;
}

@Override
public String say() {
return super.say() + "score="+score;
}
}

public class Teacher extends Person{
private double salary;

public Teacher(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

@Override
public String say() {
return super.say()+"salary="+salary;
}
}

public class Array {
public static void main(String[] args){
//现有一个继承结构如下:要求创建1个Person对象;
//2个Student对象和2个Teacher对象,统一放在数组中,并调用每个对象ssay方法
Person[] persons = new Person[5];
persons[0] = new Person("jack",20);
persons[1] = new Student("jack",18,100);
persons[2] = new Student("smith",19,50.5);
persons[3] = new Teacher("scott",30,10000);
persons[4] = new Teacher("king",50,15000);
//循环遍历数组
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].say());//动态绑定机制

}
}
}

应用实例升级:如何调用子类特有的方法,比如Teacher有一个teach,Student有一个study

public class Array {
public static void main(String[] args){
//现有一个继承结构如下:要求创建1个Person对象;
//2个Student对象和2个Teacher对象,统一放在数组中,并调用每个对象ssay方法
Person[] persons = new Person[5];
persons[0] = new Person("jack",20);
persons[1] = new Student("jack",18,100);
persons[2] = new Student("smith",19,50.5);
persons[3] = new Teacher("scott",30,10000);
persons[4] = new Teacher("king",50,15000);
//循环遍历数组
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].say());//动态绑定机制
if(persons[i] instanceof Student) {//判断person[i]的运行类型是不是Student
// ((Student}persons[i]).study();
Student student = (Student) persons[i];//向下转型
student.study();
} else if (persons[i] instanceof Teacher) {
Teacher teacher = (Teacher) persons[i];//向下转型
teacher.teach();

}

}
}
}
public class Student extends Person{
private double score;

public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}

public double getScore() {
return score;
}

public void setScore(double score) {
this.score = score;
}

@Override
public String say() {
return super.say() + "score="+score;
}
public void study() {
System.out.println("student" + getName());
}
}
public class Teacher extends Person {
private double salary;

public Teacher(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

@Override
public String say() {
return super.say() + "salary=" + salary;
}

public void teach() {
System.out.println("teacher" + getName());
}
}

 


public class Employe {
private String name;
private double salary;

public Employe(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double getAnnual() {
return 12 * salary;
}

public String getName() {
return name;
}

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

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}
}

public class Manger extends Employe{
private double bonus;

public Manger(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}

public double getBonus() {
return bonus;
}

public void setBonus(double bonus) {
this.bonus = bonus;
}
public void mamage(){
System.out.println(getName()+"正在工作");
}

@Override
public double getAnnual() {
return super.getAnnual()+getBonus();
}
}

public class Worker extends Employe{
public Worker(String name, double salary) {
super(name, salary);
}
public void work(){
System.out.println(getName()+"正在工作");
}

@Override
public double getAnnual() {
return super.getAnnual();
}
}

 

  

 

标签:JAVA,String,--,void,多态,System,println,public,name
From: https://www.cnblogs.com/maxzz/p/16886407.html

相关文章

  • [JRKSJ R5] 1-1 B
    Solution延续上一题的思路,发现只与\(1\)和\(-1\)的数量有关,设\(1\)的数量为\(a\),\(-1\)的数量为\(b\)。上一题的构造方案为\(1\)和\(-1\)交替放,再把剩余的放......
  • 使用 Nginx 如何部署 web 项目
    第一步:前往Nginx官方下载Nginx资源包,建议下载Stableversion(长期稳定版本)   第二步:将Nginx压缩包解压到本地目录中(D:\Tools)   第三步:进入到已经解压......
  • OSI传输层TCP与UDP协议、应用层简介、socket模块介绍及代码优化、半连接池的概念
    目录传输层之TCP与UDP协议应用层socket模块socket基本使用代码优化半连接池的概念传输层之TCP与UDP协议TCP与UDP都是用来规定通信方式的通信的时候可以随心所欲的聊......
  • leetcode 101 对称二叉树
    题目 给定一个二叉树,检查它是否是镜像对称的。方法一递归:classTreeNode:def__init__(self,x):self.val=xself.left=Noneself.right......
  • Centos 7 安装 Zabbix 3.4
    1、下载阿里云zabbix yum源rpm-ivhhttps://mirrors.aliyun.com/zabbix/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-1.el7.centos.noarch.rpm2、配置vim/etc/yum.r......
  • 类的各种方法和属性
    ......
  • memory hotplug
    memory_subsys_onlinememory_block_change_statememory_block_actionMEM_ONLINE:online_pagesmove_......
  • LeetCode 110. 平衡二叉树
    给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。classTreeNode:def__in......
  • 微信小程序onreachbottom不触发
    写了一个触底加载的,但是不执行。onReachBottom:function(){...}究其原因是页面并没有超过100vh,导致不会执行。page{height:101vh;}如果你看细节的话,看一下......
  • openstack绑定浮动IP时提示无可用端口
    提示: 当前网络拓扑:感觉一切都正常啊,但是就是提示无可用端口!!!!!  最终解决: (1)检查一下连接外网的这个路由器连外网的接口类型,如果是router-interface,那么应该就会提......