对象是类中的一个实例,是具体的。如学生(2010002,张三、数学系、信息与计算专业等)。
类是解决一个应该是什么的问题。对象是解决具体是什么的问题。
2.类一般需要生成对象,通过对象调用其属性以及函数。注意对象需要实例化。实例化过程其实就是为某个对象分配其存储空间。
Student s1;//定义一个对象变量,并未实例化。s1=null;
s1=new Student();//将对象实例化,将新空间首地址(引用)赋予对象s1;
//Student s1=new Student();
Studnet s2=s1;
Student s3=new Student();
3.构造函数与类同名,没有任何返回值类型
class Student
{
private string sno, sname, sdept; //属性域
private int sage;
public Student(string no,string name,string dept,int age)
{
sno = no; sname = name; sdept = dept; sage = age;
}
4.函数重载:在一个类中,有一组函数,函数名称相同,但形参的类型或个数不同。这样一组函数构成函数重载。函数重载与函数返回值类型无关。5、this引用的使用
class Student
{
private string sno, sname, sdept; //属性域
private int sage;
public Student(string sno, string sname, string sdept,int sage)
{
this.sno = sno;
this.sname = sname;
this.sdept = sdept;
this.sage = sage;
}
6.class Student
{
private string sno, sname, sdept; //属性域
private int sage;
public int Age;
public string Dept //属性访问器,Dept属性名
{
get
{
return this.sdept;
}
set
{
this.sdept = value;
}
}
7.对象数组
Student [] s=new Student[17];//new 开辟一个能够存储17个元素的对象数组
设计一个描述二维平面上点的类Point,该类需要描述点的横坐标和纵坐标,并提供属性域的set/get访问器和计算两点间距离的方法。写一个程序测试这个类。
class Pr4_3
{
static void Main(string[] args)
{
Point d1 = new Point();
d1.X = 3;
d1.Y = 4;
Point d2 = new Point(6, 5);
double dis = d1.distance(d2);
Console.WriteLine("{0} 与 {1} 的距离为 {2}", d1.ToString(), d2.ToString(), dis);
Console.ReadLine();
}
}
class Point
{
private int _x;
private int _y;
public Point()
{
}
public Point(int x, int y)
{
this._x = x;
this._y = y;
}
public int X
{
get
{
return this._x;
}
set
{
this._x = value;
}
}
public int Y
{
get
{
return this._y;
}
set
{
this._y = value;
}
}
public void moveX(int x)//X移动的距离
{
this.X = this.X + x;
}
public void moveY(int y)//Y移动的距离
{
this.Y = this.Y + y;
}
public override string ToString()
{
return "(" + _x + "," + _y + ")";
}
public double distance(Point a)//求距离
{
double jl = Math.Sqrt((this._x - a._x) * (this._x - a._x) + (this._y - a._y) * (this._y - a._y));
return jl;
}
}