2.面向对象
Posted javase-derek
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.面向对象相关的知识,希望对你有一定的参考价值。
1.1.类的定义
创建类
package derek.day06.demo; public class Student { //成员变量 String name; int age; //成员方法 public void eat(){ System.out.println("吃饭"); } public void study(){ System.out.println("学习"); } }
创建对象
package derek.day06.demo; public class demoStudent { public static void main(String[] args) { //创建对象 Student stu = new Student(); stu.name = "derek"; stu.age = 18; System.out.println(stu.name); stu.eat(); } }
1.2.private关键字
package derek.day06.demo; public class Student { //成员变量 String name; private int age; public void show(){ System.out.println(name+":"+age); } public void setAge(int num){ if (num < 100 && num > 0){ age = num; }else { System.out.println("错误的数据"); } } public int getAge(){ return age; } }
package derek.day06.demo; public class demoStudent { public static void main(String[] args) { Student stu = new Student(); stu.name = "derek"; stu.setAge(18); stu.show(); } }
1.3.构造方法
package derek.day06.demo; import org.w3c.dom.ls.LSOutput; public class Student { //成员变量 private String name; private int age; //无参数的构造方法 public Student(){ System.out.println("无参数的构造方法执行"); } //全参数的构造方法 public Student(String name, int age){ System.out.println("全参构造方法执行"); this.name = name; this.age = age; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setAge(int age){ this.age = age; } public int getAge(){ return age; } }
package derek.day06.demo; public class demoStudent { public static void main(String[] args) { Student s1 = new Student(); //无参数的构造方法执行 Student s2 = new Student("derek", 18); //全参构造方法执行 } }
1.4.Scanner类
package derek.learn; //1.导包 import java.util.Scanner; public class DemoScanner { public static void main(String[] args) { //2.创建,System.in代表从键盘进行输入 Scanner sc = new Scanner(System.in); //3.使用,获取键盘输入的int数字 int num = sc.nextInt(); System.out.println(num); //字符串 String name = sc.next(); System.out.println(name); } }
1.5.Random类
package derek.learn; import java.util.Random; public class DemoRandom { public static void main(String[] args) { Random r = new Random(); int num = r.nextInt(10); System.out.println(num); } }
1.6.ArrayList集合
package derek.learn; import java.util.ArrayList; public class DemoArrayList { public static void main(String[] args) { //创建一个ArrayList集合,里面是String类型的数据 ArrayList<String> list = new ArrayList<>(); System.out.println(list); //[] //1.向集合中添加数据 list.add("迪丽热巴"); list.add("古力娜扎"); list.add("马尔扎哈"); System.out.println(list); //[迪丽热巴, 古力娜扎, 马尔扎哈] //2.获取 System.out.println(list.get(1)); //古力娜扎 //3.删除 list.remove(1); System.out.println(list); //[迪丽热巴, 马尔扎哈] //4.获取集合长度 System.out.println(list.size()); //2 //5.遍历 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } }
以上是关于2.面向对象的主要内容,如果未能解决你的问题,请参考以下文章