面向对象的初级应用——纯代码实现
2022/5/23 23:21:42
本文主要是介绍面向对象的初级应用——纯代码实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/** * 方法定义——重载 * 方法定义——static * 没有自定义构造方法时,编译器会自动加一个无参构造方法 * 构造方法之间的调用——this */ public class Dog { public String name; private int age; public int weight; //无参构造方法 public Dog(){ //this 调用带三个参数的构造方法 this("黑宾",15,15); } //带两个参数构造方法 public Dog(int age,String name){ this.age = age; this.name = name; } public Dog(String name,int age,int weight){ this.age = age; this.name = name; this.weight = weight; this.run();//构造方法里可以访问各种普通方法 } public void setAge(int a){ this.age = age; } public int getAge(){ return age; } public void run(){ System.out.println(name+"狗跑了。。。"); } public void mesage(String name,int age){ System.out.println("狗的名字为:"+name+",年龄为:"+age); } public void mesage(String name,int age,int weight){ System.out.println("狗的名字为:"+name+",年龄为:"+age+",体重为:"+weight); } protected void action(){ System.out.println(name+"狗很听话,能根据指令进行相应的动作"); } public static void human(){ System.out.println("主人找到了狗"); } }
public class Animal { public static void main(String[] args) { //无参构造方法对象 Dog obt = new Dog(); //this 调用方法传出的值 Dog abc = new Dog(); System.out.println(abc.name+abc.getAge()+abc.weight); obt.name = "小黑"; obt.weight = 15; obt.setAge(5); obt.mesage("小白",6); obt.mesage("小黄",4,12); obt.run(); obt.action(); //obt.human(); Dog.human(); //有参构造方法 Dog oca = new Dog(15,"小蓝"); System.out.println("名字为"+oca.name+",年龄为"+oca.getAge()); } }
/** * 面向对象属性定义 * public,private,protected * this使用 * static使用 */ public class Employee { public String name; //private需要用set和get方法进行赋值和取值 private int age; //static定义的属性需要用(类名.属性名调用) public static float height; //protected定义的变量和类在同一个包中可以访问 protected double sal; int sex; String habit; //赋值 public void setAge(int a){ //this来区别参数和属性名,后面是属性名或方法名 //this代表当前对象自身 this.age = a; } //取值 public int getAge(){ return age; } public void play(){ System.out.println("我喜欢打"+habit); } }
public class EmployDemo { public static void main(String[] args) { Employee obt = new Employee(); obt.name = "张三"; obt.sex = 1; obt.habit="篮球"; obt.play(); obt.setAge(100); System.out.println("年龄为:"+obt.getAge()); obt.sal=10000; //obt.height=174.1f;虽然可以使用,但是访问的变量都是同一份 Employee.height = 179F; } }
这篇关于面向对象的初级应用——纯代码实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?