您的位置:首页 > 编程语言 > Java开发

java学习笔记:面向对象编程

2017-07-12 11:23 232 查看
//类,对象示例
class Car
{
//私有变量,只能通过开放接口访问
private String brand;	private String color;	private int wheel_num;

//构造函数:与类同名、在新建对象时会默认运行的初始化函数
Car()
{
brand="XXX";	color="XXX";	wheel_num=4;
}
Car(String brand,String color,int num)
{
//当局部变量与成员变量重名时,用this来取成员变量.this实质为对象的指针引用
this.brand=brand;		this.color=color;		wheel_num=num;
}

//开放接口,用于访问内部变量
public void setWheelNum(int num)
{
if((wheel_num>0)&&(wheel_num<5))	//轮胎数取值范围限定在1~4
wheel_num=num;
else
System.out.println("out of range");
}
public void setBrand(String brand)
{
this.brand=brand;
}
public void setColor(String color)
{
this.color=color;
}

void run()
{
System.out.println("the car is running.");
System.out.println("Info:\n"+"brand:"+brand+" color:"+color+" wheel_num:"+wheel_num);
}

public boolean IsSameWith(Car car)
{
return (this.brand==car.brand)&&(this.color==car.color)&&(this.wheel_num==car.wheel_num);
}
}

public class ObjectDemo
{
public static void main(String[] args)
{
Car car1=new Car();		Car car2=new Car("Audi","red",3);		//新建对象,car1,car2为指针引用
car1.run();		car2.run();
car1.setBrand("Audi");	car1.setColor("red");	car1.setWheelNum(3);	//对象名+'.'+函数名或变量名
car1.run();
System.out.println(car1.IsSameWith(car2));

//new Car().run();		//单次调用或传递参数时可简化为匿名对象
}
}


//static示例
/*
成员变量与静态变量的区别:
1.成员变量生命周期与对象相图,静态变量生命周期与类相同
2.成员变量只能被对象调用,静态变量能被对象与类名调用
3.成员变量存放在堆内存中,静态变量存放在方法区(共享数据区)中
4.成员变量只能被非静态函数调用,静态变量能被静态函数与非静态函数调用
*/
class Person
{
private String name; private String age;
//static修饰共享变量,且共享变量先于对象存在,因此可以用"类名.共享变量名"形式访问(非私有条件下)
static String country="CN";

public static void method()
{
System.out.println(Person.country);
}

//以下方法不能定义为static,因为需要用到成员变量
public void setName(String name,String age)
{
this.name=name; this.age=age;
}
public void show()
{
System.out.println(this.name+"-"+this.age+"-"+Person.country);
}
}

public class Demo
{
static //静态代码块随着类的加载而运行
{
System.out.println("static code block is running...");
}

//主函数是静态的,只能调用静态方法与变量
public static void main(String[] args)
{
Person.method(); //调用类中的静态方法不需要新建对象
StaticDemo();
}

public static void StaticDemo() //静态变量节省内存使用的示例
{
Person person1=new Person(); Person person2=new Person(); Person person3=new Person();
person1.setName("Daya1","18"); person2.setName("Daya2","19"); person3.setName("Daya3","20");
person1.show(); person2.show(); person3.show();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 面向对象编程