public class MethodDemo { public int add(int a,int b) { return a+b; } public static void main(String[] args) { MethodDemo m =new MethodDemo(); int sum = m.add(1,2); System.out.println("sum=" + sum); } }
public class People { private String name; private int age; public void show() { System.out.println("姓名:" + name +"年龄:" + age ); } public People() { } public People(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age > 0 && age < 150){ this.age = age; }else{ this.age = 18; System.out.println("错误"); } } }
import org.junit.Test; import static org.junit.Assert.*; public class PeopleTest { @Test public void test01(){ People people = new People(); people.show(); } @Test public void test02() { People people = new People("牛",-1); people.setAge(-1); people.show(); } }
public class Person { String name; int old; public void show() { System.out.println("年龄:" + old +"姓名:" + name ); } public static void main(String[] args) { Person p = new Person(); p.show(); p.name = "zhangfei"; p.old = 30; p.show(); } }
import static org.junit.Assert.*; public class PersonTest { public void test01(){ Person p = new Person(); p.show(); } }
public class Phone { String brand; double price; boolean bf; public void show() { System.out.println("品牌:" + ",价格" + price + "ab" + bf) ; } public static void main(String[] args) { Phone p = new Phone(); p.show(); p.brand = "Nokia"; p.price = 598.5; p.show(); } }
public class Point { int x; int y; public static void main(String[] args) { Point point = new Point(); System.out.println("x="+point.x); System.out.println("y="+point.y); point.x = 3; point.y = 4; System.out.println("x="+point.x); System.out.println("y="+point.y); } }
import java.util.Scanner; public class Rectangle { Rectangle(int width,int length) { } public void getArea(){ } public void getPer(){ } public void showAll(){ } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("kuan"); int width = scanner.nextInt(); System.out.println("chang"); int length = scanner.nextInt(); } } 4.1 面向过程(POP)与面向对象(OOP) 面向过程:Procedure Oriented Programming 强调的是功能行为,以函数为最小单位,考虑怎么做; 面向对象:Object Oriented Programming 强调具备了功能的对象,以类/ 对象为最小单位,考虑谁来做; 4.2 类和对象 类:对一类事物的描述,是抽象的,概念上的定义; 对象:是实际存在的该类事物的每个个体,因而也称为实例(instance); 4.2.1 Java类及类的成员 属性:对应类中的成员变量; 行为:对应类中的成员方法; 4.2.2 类与对象的创建及使用 设计类,就是设计类的成员 属性 == 成员变量 == field == 域、字段; 方法 == 成员方法 == 函数 == method; 创建类的对象 == 类的实例化 == 实例化类; 类和对象的使用(面向对象思想落地的实现) 创建类,设计类成员; 创建类的对象; 通过“对象·属性”或“对象·方法”调用对象的结构; 如果创建了一个类的多个对象,则每个对象都独立拥有一套类的属性(非static) 意味着:如果我们修改一个对象的属性a,则不影响另外一个对象属性a 的值;