JAVA的类

类与调用

 1 public class initCal {
 2     private int num1;
 3     private int num2;
 4     private char option;
 5 
 6     public void harvest(int n1, int n2, char o) {
 7         num1 = n1;
 8         num2 = n2;
 9         if (o == '+' || o == '-' || o == '*' || o == '/') {
10             option = o;
11         }
12     }
13     public void cal() {
14         switch (option) {
15         case '+':
16             System.out.println(num1 + num2);
17             break;
18         case '-':
19             System.out.println(num1 - num2);
20             break;
21         case '*':
22             System.out.println(num1 * num2);
23             break;
24         case '/':
25             System.out.println(num1 / num2);
26             break;
27         default:
28             break;
29         }
30     }
31 }
1 public class cpu {
2 
3     public static void main(String[] args) {
4         initCal c = new initCal();
5         c.harvest(1, 2, '+');
6         c.cal();
7     }
8 }

构造函数

 1 class baby {
 2     int num1;
 3     String str1;
 4 
 5     //构造代码块在创建对象的时候就会执行 创建一次,执行一次
 6     {
 7         System.out.println("构造代码块执行了");
 8     }
 9 
10     public baby(int n1, String s1) {
11         this.num1 = n1;
12         this.str1 = s1;
13     }
14 
15     public static void main(String[] args) {
16         baby ba = new baby(1, "hello");
17         baby ba2 = new baby(1, "hello");
18     }
19 }

抽象类  继承

Animal类

 1 abstract class Animal {
 2     String name;
 3     String color;
 4 
 5     public Animal(String name,String color) {
 6         this.name=name;
 7         this.color;
 8     }
 9 
10     public void eat() {
11         System.out.print("吃东西");
12     }
13     
14     public abstract void run();
15 }

Dog类

 1 public class Dog extends Animal {
 2 
 3     public Dog(String name, String color) {
 4         super(name, color);
 5     }
 6 
 7     public void run() {
 8         System.out.print(color + name + "四条腿跑");
 9     }
10 
11     public static void main(String[] args) {
12         Dog dg = new Dog("海狗", "黄色");
13         dg.run();
14     }
15 
16 }

Fish类

 1 public class fish extends Animal {
 2 
 3     public fish(String name, String color) {
 4         super(name, color);
 5         // TODO Auto-generated constructor stub
 6     }
 7 
 8     public void run() {
 9         System.out.print(color + name + "游的快");
10     }
11 
12     public static void main(String[] args) {
13         fish fh = new fish("小鱼", "红色");
14         fh.run();
15     }
16 
17 }
原文地址:https://www.cnblogs.com/ronle/p/9805378.html