类与对象的认知
最近学习了类与对象,我对java有了进一步的认识,java里面可以将万事万物包装为对象,以对象来解决问题容易多了,不用在乎过程。
oop:面向对象程序语言设计
oop语言的三大特征:继承,封装,多态
1:类是什么?
类就相当于一个模板,用它来创造对象
一个类可以创造多个对象
2:什么是对象?
对象就是一个类的实例,
3:如何创造出一个对象?
class Person{
public static void main(String[] args){
public String name; //属性 成员变量 实例成员变量 (通过对象的引用访问)
public int age;
public static int count=10;
Person person=new Person(); //person是对象的引用,,,,,new Person()是一个对象
}
}
对象是怎么产生的?
一个对象的产生分为两步:为对象分配内存,调用合适的构造方法
(构造方法走完,对象才产生)
1.类与对象里面要特别注意 方法和属性是否是被static所修饰的,被static修饰的方法为静态方法,也称之为类方法,因为类方法与实例无关,只和类有关,调用也通过类名调用
2.静态方法里面不能调用非静态方法
class TestDemo{
public int a;
public static int count;
public static void change() {
count = 100;
//a = 10; error 不可以访问非静态数据成员
}
}
public class Main{
public static void main(String[] args) {
TestDemo.change();//无需创建实例对象 就可以调用 System.out.println(TestDemo.count);
}
}
从这段代码我们可以清楚的明白static方法只能调用静态属性和方法
public class test {
private String name;
private int age;
private static int count;
public test() {
this.name=name;
this.age=age;
this.count=count;
}
public void print() {
System.out.println(this.name+"的分数是"+this.count);
}
public static void main(String[] args) {
test aTest=new test();
aTest.age=16;
aTest.name="马主任";
aTest.count=99;
aTest.print();
System.out.println(aTest.name+"的年龄是"+aTest.age+"岁");
}
}
马主任的分数是99
马主任的年龄是16岁
上面的代码就可以看出非静态方法里面可以方法静态属性,但是如果把这个方法
变为静态的,就会报错。
还有特别注意:this指的是当前对象的引用
类与对象就说到这里了。