In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the method of java object-oriented programming". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the method of java object-oriented programming".
Case "Pet Store"
1. Introduction
Features:
a. Pet shops can buy and sell pets.
b. Pets have the ability to eat.
c. Pet owners can buy pets in pet shops, name their pets and feed them.
two。 Analysis:
Through the introduction of the above functions and the idea of object-oriented programming, the following results can be obtained:
a. Pet stores have the function of buying and selling pets (that is, pet store category, named PetShop). At the same time, pets in the store need to have a HashMap collection, called pets, similar to cages in pet stores, where all kinds of pets are stored for customers to buy.
b. Basic pet specific attributes, such as name, breed and other attributes (i.e. pet category, named pet)
c. Pet shops sell pets, then there are all kinds of pets, such as pet dogs, pet cats (that is, pet dogs, named Dog; pet cats, named Cat)
d. Pet owners have the function of buying and feeding pets (that is, pet master human, named: Master)
3. Coding
Through the analysis, we have a general idea of how we are going to code, so let's use its four characteristics in the form of coding.
a. Package characteristic
Encapsulation (English: Encapsulation) is a method that wraps and hides the implementation details of an abstract function interface.
Encapsulation can be thought of as a protective barrier to prevent code and data of this class from being randomly accessed by code defined by external classes.
With an understanding of the concept of encapsulation, we roughly know that the unique properties of pets can not be changed at will, so can we encapsulate it as follows:
Import java.util.ArrayList
Import java.util.List
/ * Encapsulation feature
* 1. Modified by the private modifier, the outside cannot directly access * 2. Provide indirect access through the get,set method
* * /
Public class Pet {
Private String id
Private String strain
Private int loveNum
Private int num
Private String name
Public static List petSpecies
Static {/ / static code block, which will only be executed the first time the constructor is executed, initializing the petSpecies collection
PetSpecies = new ArrayList ()
PetSpecies.add (new Pet (0001, Persian Cat, 0999999)
PetSpecies.add (new Pet (002, Garfield, 09999))
PetSpecies.add (new Pet (003, husky, 09999))
PetSpecies.add (new Pet, Chinese Pastoral Dog, 09999)
PetSpecies.add (new Pet ("005", "Chinese Pastoral Cat", 09999)
PetSpecies.add (new Pet, Shepherd Dog, 09999)
System.out.println ("id\ t breed")
For (Pet pet:petSpecies) {
System.out.println (pet)
}
}
Public Pet (String id,String strain, int loveNum,int num) {
This.strain = strain
This.id = id
This.loveNum = loveNum
This.num = num
}
Public Pet () {
}
/ / when buying pets in the store, return pets to the merchant according to the id and quantity selected by the merchant.
Public static Pet givePetToShop (String petId,int petNum) {
Pet pet = null
For (Pet p:petSpecies) {
If (p.getId () .equals (petId)) {
Pet = p
Pet.setNum (petNum)
Return pet
}
}
Return pet
}
Public void eat () {
System.out.println (strain+ "eating happily")
}
@ Override// overrides the toString method
Public String toString () {
Return this.id+ "\ t" + this.strain + "\ t"
}
@ Override// overrides the hashCode method
Public int hashCode () {
Return this.getId () .hashCode ()
}
@ Override// overrides the equals method
Public boolean equals (Object obj) {
If (obj instanceof Pet) {/ / determines whether the obj class is a Pet class or a subclass of Pet
Pet other = (Pet) obj
If (this.getId () .equals (other.getId ()
If (this.getStrain () .equals (other.getStrain ()
Return true
}
}
}
Return false
}
Public int getNum () {
Return num
}
Public void setNum (int num) {
This.num = num
}
Public String getName () {
Return name
}
Public void setName (String name) {
This.name = name
}
Public String getId () {
Return id
}
Public void setId (String id) {
This.id = id
}
Public String getStrain () {
Return strain
}
Public void setStrain (String strain) {
This.strain = strain
}
Public int getLoveNum () {
Return loveNum
}
Public void setLoveNum (int loveNum) {
This.loveNum = loveNum
}
}
b. Inherit property
Inheritance is that the subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior of the parent class.
c. Polymorphisms
Polymorphism is the ability of the same behavior to have many different forms or forms of expression.
After understanding the concepts of inheritance and polymorphism, we roughly know that cats and dogs belong to pets, then cats and dogs can inherit the characteristics and behavior of pets, and each pet's behavior has different forms, as shown in the following code:
/ * inherit features * 1. Dogs inherit the characteristics of pets * polymorphism * 2. Dogs rewrite eating behavior, that is, dog eating behavior is a form of pet eating * * / public class Dog extends Pet {private String name
Public Dog () {
}
Public Dog (String id,String strain,int loveNum,int num,String name) {
Super (id,strain,loveNum,num); / / call the parameter constructor of the parent class
This.name = name
}
@ Override// overrides the eat () method in the inherited Pet class
Public void eat () {
System.out.println ("pet dog" + name + ": eat so full, intimacy plus 5!")
This.setLoveNum (this.getLoveNum () + 5); / / intimacy value plus 5
}
Public String getName () {
Return name
}
Public void setName (String name) {
This.name = name
}
}
/ * inherit features * 1. Cats inherit the characteristics of pets * polymorphism * 2. Cats also rewrite eating behavior, that is, cat eating behavior is a form of pet eating * * / public class Cat extends Pet {
Private String name
Public Cat () {
}
Public Cat (String id,String strain,int loveNum,int num,String name) {
Super (id,strain,loveNum,num)
This.name = name
}
@ Override// rewrites the eat () method
Public void eat () {
System.out.println ("Pet Cat" + name + ": enough to eat, intimacy plus 3!")
This.setLoveNum (this.getLoveNum () + 3)
}
Public String getName () {
Return name
}
Public void setName (String name) {
This.name = name
}
}
Import java.util.HashMap
Import java.util.Iterator
Import java.util.Map
Import java.util.Set
/ * *
*
* @ ClassName: PetShop
* @ Description: pet store with functions such as buying and selling pets (method)
, /
Public class PetShop {
Private static String name;// Store name
Private static String address;// store address
Private boolean isHasCustom;// judges whether there are customers coming.
Private static HashMap pets;// stores the collection of pets. The key is the Pet class, and the value is the number of pets.
Static {/ / static code block, initializing pets in the store, will only be executed the first time the constructor is executed
Name = "all right, come again"
Address = "Erqi District Haiwei Science and Technology Park"
System.out.println ("-" + name+ "pet store -" + address+ "branch -")
Cat boSiCat = new Cat ("001", "Persian Cat", 0pr 3, "")
Cat coffeCat = new Cat ("002", "Garfield", 0Phone2, "")
Dog haShiqi = new Dog ("003", "husky", 0pr 2, "")
Dog tianYuanQuan = new Dog ("004", "Chinese Pastoral Dog", 0meme 4, "")
Pets = new HashMap ()
Pets.put (boSiCat, boSiCat.getNum ())
Pets.put (coffeCat,coffeCat.getNum ())
Pets.put (haShiqi, haShiqi.getNum ())
Pets.put (tianYuanQuan,tianYuanQuan.getNum ())
}
Public PetShop (String name, String address) {
Super ()
This.isHasCustom = false
}
Public PetShop () {
This.isHasCustom = false
}
/ * *
* Pet display
, /
Public void showAllPet () {
System.out.println ("No.\ t varieties\ t quantity")
Set entry = pets.entrySet ()
Iterator it = entry.iterator ()
While (it.hasNext ()) {
System.out.println (it.next ())
}
}
/ / Pet is returned according to id
Public Pet getPetById (String id) {
If (id! = null) {
For (Pet p:pets.keySet ()) {
If (p.getId () .equals (id)) {
Return p
}
}
}
Return null
}
/ * *
* when purchasing pets, the overridden equals method and hashCode method are used here.
, /
Public boolean purchasePets (Pet pet) {
Set entry = pets.entrySet ()
Iterator it = entry.iterator ()
While (it.hasNext ()) {
If (it.next (). Equals (pet)) {/ / if the store already contains this pet, just update the number of this pet
Pets.put (pet, pets.get (pet) + pet.getNum ())
Return true
}
}
Pets.put (pet, pet.getNum ())
Return true
}
/ * *
* add a pet, and if the pet is already included, only change the number of pets
This feature requires overriding the hashCode () and equals () methods first.
, /
Public boolean addPetToShop (Pet pet) {
If (pet = = null)
Return false
If (pets.containsKey (pet)) {
Pets.put (pet, pets.get (pet) + pet.getNum ())
Return true
} else {
Pets.put (pet, pet.getNum ())
Return true
}
}
/ * *
* selling pets from stores
, /
Public boolean removePetFromShop (Pet pet) {
If (pet = = null)
Return false
For (Pet p:pets.keySet ()) {
If (p.equals (pet) & & pets.get (p) = = pet.getNum ()) {
Pets.remove (p)
Return true
}
If (p.equals (pet) & & pets.get (p) > pet.getNum ()) {
Pets.put (pet, pets.get (p)-pet.getNum ())
Return true
}
If (p.equals (pet) & & pets.get (p)
< pet.getNum()) { return false; } } return false; } /** * 判断是否有顾客前来 * @return */ public boolean isHasCustom() { return isHasCustom; } public void setHasCustom(boolean isHasCustom) { this.isHasCustom = isHasCustom; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public HashMap getPets() { return pets; } } import java.util.ArrayList; import java.util.List; /** * * @ClassName: Master * @Description:主人类,有购买宠物等行为(也就是方法) */ public class Master { private String name; List myPets; public Master() { myPets = new ArrayList(); } public Master(String name) { myPets = new ArrayList(); this.name = name; } //去宠物店的行为 public boolean goPetShop(PetShop shop) { shop.setHasCustom(true); return true; } //浏览宠物行为 public void scanPet(PetShop shop) { if(goPetShop(shop)) { shop.showAllPet(); }else { System.out.println("暂时无法浏览宠物!"); } } //离开商店的行为 public void outShop(PetShop shop) { shop.setHasCustom(false); } //更新myPets中的宠物的信息 public boolean updateMyPets(Pet pet) { for(int i = 0;i < myPets.size();i++) { if(myPets.get(i).equals(pet)) { myPets.get(i).setName(pet.getName()); myPets.get(i).setNum(pet.getNum()); myPets.get(i).setLoveNum(pet.getLoveNum()); return true; } } return false; } //给宠物命名并更新宠物 public boolean setNameToPet(Pet pet,String name) { if(pet != null && name != null) { pet = getPetStrain(pet);//获取宠物的种类 pet.setName(name);//如果是Dog类,就执行Dog类的方法 pet.setLoveNum(50); updateMyPets(pet); return true; } return false; } //购买宠物 public boolean buyPet(Pet pet,PetShop shop) { if(pet != null) { pet.setNum(1); myPets.add(pet); shop.removePetFromShop(pet);//这里宠物商店里的宠物要减少一只 return true; } else return false; } /** * 给宠物喂食 */ public boolean feedPet(Pet pet) { if(pet!= null) { getPetStrain(pet).eat(); return true; } return false; } //查看所拥有的宠物信息 public boolean scanMyPets() { if(myPets.size()==0) { return false; } System.out.println("id\t品种\t名字\t亲密值"); for(Pet p:myPets) { System.out.print(p.getId()+"\t"+p.getStrain()+"\t"+p.getName() +"\t"+p.getLoveNum()+"\n"); } return true; } //查看某个宠物的亲密值 public void loveNumWithPet(String name) { Pet pet = getMyPetByName(name); System.out.println(pet.getName() + ":我们的亲密值为"+pet.getLoveNum()); } //通过名字查找宠物 public Pet getMyPetByName(String petName) { for(Pet pet:myPets) { if(pet.getName().equals(petName)) { return pet; } } return null; } //获取宠物的品种 public Pet getPetStrain(Pet pet) { if(pet.getStrain().equals("波斯猫")||pet.getStrain().equals("加菲猫")) { return((Cat)(pet)); } if(pet.getStrain().equals("哈士奇")||pet.getStrain().equals("中华田园犬")) { return((Dog)(pet)); } return null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getMyPets() { return myPets; } public void setMyPets(List myPets) { this.myPets = myPets; } } import java.util.ArrayList; import java.util.List; /** * * @ClassName: Master * @Description:主人类,有购买宠物等行为(也就是方法) * @author yemao * @date 2019年3月21日 */ public class Master { private String name; List myPets; public Master() { myPets = new ArrayList(); } public Master(String name) { myPets = new ArrayList(); this.name = name; } //去宠物店的行为 public boolean goPetShop(PetShop shop) { shop.setHasCustom(true); return true; } //浏览宠物行为 public void scanPet(PetShop shop) { if(goPetShop(shop)) { shop.showAllPet(); }else { System.out.println("暂时无法浏览宠物!"); } } //离开商店的行为 public void outShop(PetShop shop) { shop.setHasCustom(false); } //更新myPets中的宠物的信息 public boolean updateMyPets(Pet pet) { for(int i = 0;i < myPets.size();i++) { if(myPets.get(i).equals(pet)) { myPets.get(i).setName(pet.getName()); myPets.get(i).setNum(pet.getNum()); myPets.get(i).setLoveNum(pet.getLoveNum()); return true; } } return false; } //给宠物命名并更新宠物 public boolean setNameToPet(Pet pet,String name) { if(pet != null && name != null) { pet = getPetStrain(pet);//获取宠物的种类 pet.setName(name);//如果是Dog类,就执行Dog类的方法 pet.setLoveNum(50); updateMyPets(pet); return true; } return false; } //购买宠物 public boolean buyPet(Pet pet,PetShop shop) { if(pet != null) { pet.setNum(1); myPets.add(pet); shop.removePetFromShop(pet);//这里宠物商店里的宠物要减少一只 return true; } else return false; } /** * 给宠物喂食 */ public boolean feedPet(Pet pet) { if(pet!= null) { getPetStrain(pet).eat(); return true; } return false; } //陪宠物玩耍 public boolean playWithPet(Pet pet) { if(pet!= null) { getPetStrain(pet).play(); return true; } return false; } //查看所拥有的宠物信息 public boolean scanMyPets() { if(myPets.size()==0) { return false; } System.out.println("id\t品种\t名字\t亲密值"); for(Pet p:myPets) { System.out.print(p.getId()+"\t"+p.getStrain()+"\t"+p.getName() +"\t"+p.getLoveNum()+"\n"); } return true; } //查看某个宠物的亲密值 public void loveNumWithPet(String name) { Pet pet = getMyPetByName(name); System.out.println(pet.getName() + ":我们的亲密值为"+pet.getLoveNum()); } //通过名字查找宠物 public Pet getMyPetByName(String petName) { for(Pet pet:myPets) { if(pet.getName().equals(petName)) { return pet; } } return null; } //获取宠物的品种 public Pet getPetStrain(Pet pet) { if(pet.getStrain().equals("波斯猫")||pet.getStrain().equals("加菲猫")) { return((Cat)(pet)); } if(pet.getStrain().equals("哈士奇")||pet.getStrain().equals("中华田园犬")) { return((Dog)(pet)); } return null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getMyPets() { return myPets; } public void setMyPets(List myPets) { this.myPets = myPets; } } import java.util.Scanner; /** * @ClassName: Test * @Description: 测试类 * ArrayList在遍历的时候如果同时删除元素就会抛出java.util.ConcurrentModificationException异常 */ public class Test { private static Scanner sc = new Scanner(System.in);// 实例化一个输入流对象 public static void main(String[] args) { PetShop shop = new PetShop(); Master master = new Master("明明");//实例化一个宠物主人,明明 Pet pet = null; int circleNum = 0;// 表示while循环的次数 int choiceNum = -1;// 操作数 String petId = ""; while(choiceNum == -1) { circleNum++; if(circleNum == 1) { System.out.println("**进购宠物**"); new Pet();//初始化进购的宠物种类,为的是执行Pet.java里的静态代码块 } System.out.println("选择操作:1、进购\t2、离开"); choiceNum = sc.nextInt(); if(choiceNum == 1) { System.out.println("请输入要进购宠物的id和数量"); pet = Pet.givePetToShop(sc.next(), sc.nextInt()); if(pet != null) { shop.addPetToShop(pet);//商家进购此宠物 System.out.println("进购成功!"); choiceNum = -1; }else {//表示输入的id有误,没有此类宠物 System.out.println("没有此类宠物!"); choiceNum = -1; } }else if(choiceNum == 2) { choiceNum = -2; }else { System.out.println("输入有误!请重新选择!"); } } circleNum = 0; master.goPetShop(shop);// 去宠物店 while (shop.isHasCustom()) { circleNum++; if (circleNum == 1) { System.out.println(shop.getName() + ":欢迎" + master.getName() + "光临本店"); } else { System.out.println(shop.getName() + ":请选择要进行的操作:1.浏览宠物\t2.离开本店"); choiceNum = sc.nextInt();// 从键盘控制台接收一个整数 if (choiceNum == 1) { master.scanPet(shop);// 明明浏览宠物 System.out.println(shop.getName() + ":请输入编号来选择您想要的宠物:"); petId = sc.next(); pet = shop.getPetById(petId);// 通过id获得宠物 if (pet == null) { System.out.println(shop.getName() + ":请输入正确的编号!"); } else { System.out.println(shop.getName() + ":您选择了" + pet + ",是否确认购买?1.确认购买\t2.在考虑一下"); choiceNum = sc.nextInt(); if (choiceNum == 1) { master.buyPet(pet, shop);// 明明购买这个宠物 System.out.println(shop.getName() + ":恭喜您获得新宠!"); } } } else if (choiceNum == 2) { master.outShop(shop);// 离开商店 System.out.println(shop.getName() + ":客官慢走,欢赢下次光临!"); circleNum = 0; } } } System.out.println(master.getName()+ "离开了" + shop.getName() + "宠物店,正在回家的路上......."); String petName = null; while (true) { circleNum++; if (circleNum == 1) { System.out.println(master.getName() + "回到家了"); System.out.println(master.getName() + ":给新买的宠物们起个名吧!嘻嘻!"); for (Pet p : master.getMyPets()) { System.out.println("这只宠物是" + p.getStrain() + ",给他起个名字:"); petName = sc.next(); if (master.setNameToPet(pet, petName)) {// 给宠物起名字 System.out.println(pet.getName() + ":有了新名字很开心!亲密值增加了" + pet.getLoveNum()); } } System.out.println(master.getName() + ":所有的宠物都起好名字了,他们更喜欢我了!"); System.out.println("请选择操作:1.给宠物喂食\t" +"2.获取所有的宠物信息\t3.退出:"); choiceNum = sc.nextInt(); } if (choiceNum >4 | | choiceNum < 1) {
System.out.println ("incorrect input!")
} else {
While (choiceNum = = 1) {
System.out.println (master.getName () + ": who would you like to feed first? call the roll at will!")
Pet = master.getMyPetByName (sc.next ())
Master.feedPet (pet); System.out.println ("Please select actions: 1. Feed pets\ t" + "2. Get all pet information\ T3. Exit:")
ChoiceNum = sc.nextInt ()
}
While (choiceNum = = 2) {
Master.scanMyPets ()
System.out.println ("Please select actions: 1. Feed pets\ t" + "2. Get all pet information\ T3. Exit:")
ChoiceNum = sc.nextInt ()
}
If (choiceNum = = 3)
Break
}
}
System.out.println ("Program exited!")
}
} Thank you for reading, the above is the content of "what is the method of java object-oriented programming". After the study of this article, I believe you have a deeper understanding of what the method of java object-oriented programming is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.