zoukankan      html  css  js  c++  java
  • JAVA_SE基础——25.面向对象练习

    昨晚我写了篇面向对象的内存分析,今天我们来做个小练习。。


    需求:

     使用java描述一个车与修车厂两个事物, 车具备的公共属性:轮子数、 名字、 颜色 ,还
    具备跑的功能行为。跑之前要检测轮子是否少于了4个,如果少于了4个,那么要送到修车厂修理,
    修车厂修理之后,车的轮子数要补回来4个。 然后车就继续的跑起来。


    修车厂: 具备公共属性: 名字、 地址、 电话。
    公共的行为: 修车。

    --------------------------------------------------------------------------------------------------------------

    初学者的经典错误:
    1. 变量在同一个作用域(大括号)上是可以直接访问的。
    2. 如果一个类要访问另外一个类变量时,那么这时候就只能通过创建对象进行访问。(仅对于目前正确)


    生气

    //车类
    class Car{
    	
    	//事物的公共属性使用成员变量描述	
    	String name ; // 名字
    
    	String color; //名字
    
    	int wheel; //轮子数
    	
    	//事物的公共行为使用函数描述
    	public void run(){
    		if(wheel>=4){
    			System.out.println(name+wheel+"个轮子飞快跑起来..");
    		}else{
    			System.out.println(name+"不够4个轮子了,赶快去修理");
    		}
    	}
    }
    
    //修车厂
    class CarFactory{
    	
    	String name;//名字
    	
    	String address ;//地址
    	
    	String tel;	//电话
    
    	//修车公共行为 ------ 返回值类型、 未知的参数
    	public void repair(Car c){
    		if(c.wheel>=4){
    			System.out.println("告诉你,费了很大力气修好了,给钱");
    		}else{
    			c.wheel = 4;
    			System.out.println("修好了,给钱!!");	
    		}
    	}
    }
    
    
    class Demo2 
    {
    	public static void main(String[] args) {		
    		//0x98
    		Car c = new Car();
    		//给车对象赋予属性值
    		c.name = "比亚迪";
    		c.color = "黑色";
    		c.wheel = 4;
    		
    		for(int i = 0 ; i<100 ; i++){
    			c.run();
    		}
    		c.wheel = 3;
    		c.run();
    
    		//创建修车厂对象
    		CarFactory f = new CarFactory();
    		//给修车厂赋予属性值
    		f.name = "集群宝修车厂";
    		f.address = "韵泰商业广场一楼";
    		f.tel = "020-1234567";
    		//调用修车的修车
    		f.repair(c);
    		c.run();	
    	}
    }


    通过代码的注释 有些基础的同学 应该都能看的懂,如果还不懂请看我的上一章 24.面向对象的内存分析



  • 相关阅读:
    20200226 Java IO流——廖雪峰
    20200225 Java 多线程(2)-廖雪峰
    20200225 Java 多线程(1)-廖雪峰
    20200224 尚硅谷ElasticSearch【归档】
    20200224 一 概述
    20200222 尚硅谷Dubbo【归档】
    20200222 四、dubbo原理
    Improved robustness of reinforcement learning policies upon conversion to spiking neuronal network platforms applied to Atari Breakout game
    Reinforcement learning in populations of spiking neurons
    Solving the Distal Reward Problem through Linkage of STDP and Dopamine Signaling
  • 原文地址:https://www.cnblogs.com/Jhaiha0/p/8465319.html
Copyright © 2011-2022 走看看