title: Java基础语法(9)-面向对象之类的成员 html
blog: CSDNjava
data: Java学习路线及视频程序员
两者都是一种思想,面向对象是相对于面向过程而言的。面向过程,强调的是功能行为,以函数为最小单位,考虑怎么作。面向对象,将功能封装进对象,强调具有了功能的对象,以类/对象为最小单位,考虑谁来作。数组
面向对象更增强调运用人类在平常的思惟逻辑中采用的思想方法与原则,如抽象、分类、继承、聚合、多态等。数据结构
面向对象的三大特征函数
封装 (Encapsulation)工具
继承 (Inheritance)学习
多态 (Polymorphism)测试
修饰符 class 类名 { 属性声明; 方法声明; } 说明:修饰符public:类能够被任意访问类的正文要用{ }括起来
public class Person{ private int age ; //声明私有变量 age public void showAge(int i) { //声明方法showAge( ) age = i; } }
类名 对象名 = new 类名();
Animal xb=new Animal();
对象名.对象成员的方式访问对象成员(包括属性和方法)
//Animal类 public class Animal { public int legs; public void eat(){ System.out.println(“Eating.”); } public viod move(){ System.out.println(“Move.”); }
public class Zoo{ public static void main(String args[]){ //建立对象 Animal xb=new Animal(); xb.legs=4;//访问属性 System.out.println(xb.legs); xb.eat();//访问方法 xb.move();//访问方法 } }
修饰符 数据类型 属性名 = 初始化值 ;.net
public class Person{ private int age; //声明private变量 age public String name = “Lila”; //声明public变量 name }
class Person{ //1.属性 String name;//姓名--成员变量 int age = 1;//年龄 boolean isMale;//是不是男性 public void show(String nation){ //nation:局部变量 String color;//color:局部变量 color = "yellow"; } } //测试类 class PersonTest{ public static void main(String[] args){ Person p = new Person(); p.show(“USA”); } }
public class Person{ private int age; public int getAge() { //声明方法getAge() return age; } public void setAge(int i) { //声明方法setAge age = i; //将参数i的值赋给类的成员变量age } }
修饰符 返回值类型 方法名(参数类型 形参1, 参数类型 形参2, ….){ 方法体程序代码 return 返回值; } 修饰符:public,缺省,private, protected等
无返回值 | 有返回值 | |
---|---|---|
无形参 | void 方法名(){} | 返回值的类型 方法名(){} |
有形参 | void 方法名(形参列表){} | 返回值的类型 方法名(形参列表){} |
注意
方法的重载
在同一个类中,容许存在一个以上的同名方法,只要它们的参数个数或者参数类型不一样便可。
与返回值类型无关,只看参数列表,且参数列表必须不一样。(参数个数或参数类型)。调用时,根据方法参数列表的不一样来区别。
//返回三个整数的和 int add(int x,int y,int z){ return x+y+z; }
//可变参数 public void test(String a,int... b){ for (int i : b) { Log.i("test:","b:" + i); } }
Person p = new Person(“Peter”,15);
修饰符 类名 (参数列表) { 初始化语句; }
//建立Animal类的实例 //调用构造器,将legs初始化为4。 public class Animal { private int legs; // 构造器 public Animal() { legs = 4; } public void setLegs(int i) { legs = i; } public int getLegs() { return legs; }
代码块的做用:
代码块的分类:
静态代码块:用static修饰的代码块
非静态代码块:没有static修饰的代码块
class Person { public static int total; static { total = 100; System.out.println("in static block!"); } } public class PersonTest { public static void main(String[] args) { System.out.println("total = " + Person.total); System.out.println("total = " + Person.total); } }
程序中成员变量赋值的执行顺序
class Outer { private int s; public class Inner { public void mb() { s = 100; System.out.println("在内部类Inner中s=" + s); } } public void ma() { Inner i = new Inner(); i.mb(); } } public class InnerTest { public static void main(String args[]) { Outer o = new Outer(); o.ma(); } }
2020-3-31: Java基础语法(6)-注释
2020-3-31: Java基础语法(7)-数组
今日好文推荐
今日资料推荐