定义一个学生对象student,包含四个属性:学号、姓名、年龄、性别(属性值自行定义),并且包含一个方法:play,这个方法可以在控制台输出最喜欢玩的游戏。
定义好student对象后,在控制台打印输出此对象的所有属性,最后调用对象中的方法。
package demo; import java.util.Scanner; public class qet { public static int id; public static String name; public static int age; public static String sex; public static String plays; static Scanner input =new Scanner(System.in); public static void main(String[] args) { play(); } public static void play() { System.out.println("请输入学号:"); id =input.nextInt(); System.out.println("请输入名字:"); name =input.next(); System.out.println("请输入年龄:"); age =input.nextInt(); System.out.println("请输入性别:"); sex =input.next(); System.out.println("请输入最喜欢的游戏:"); plays =input.next(); System.out.print("学员的信息如下:"+"\n"+"学号="+id+",名字="+name+",年龄="+age+",性别="+sex+"\n"+"最喜欢的游戏:"+plays); } }
先了解一下js构造函数,然后根据想要的方法和属性写就行了
//对象
let Student = {
number: "",
name: "",
age: "",
sex: "",
play: function () {
console.log('我最喜欢玩游戏')
}
}
console.log(Student);
Student.play();
//函数对象
function Student1(number, name, age, sex, game) {
this.number = number;
this.name = name;
this.age = age;
this.sex = sex;
this.play = function () {
console.log('我最喜欢玩' + game);
}
}
var my = new Student1(1, '威威', 15, '男', '王者');
console.log(my);
my.play();
//class类
class Parent {
constructor(number, name, age, sex, game) {
this.number = number;
this.name = name;
this.age = age;
this.sex = sex;
this.play = function () {
console.log('我最喜欢玩' + game);
}
}
};
const child = new Parent(1, '威威', 15, '男', '王者');
console.log(child);
child.play();
分为ES5.1版本之前和ES6
在ES5.1之前使用的是构造函数+原型的方式
function Student(number, name, age, sex, game) {
this.number = number;
this.name = name;
this.age = age;
this.sex = sex;
}
Student.prototype.play = function(gameName){
console.log('我最喜欢玩' + gameName);
}
var student = new Student("007", "张三", 18, "男", "王者");
console.log(student);
student.play();
通常情况下在构建一个类的时候,会将方法写在其原型上
ES6语法
class Student {
constructor(number, name, age, sex, game) {
this.number = number;
this.name = name;
this.age = age;
this.sex = sex;
};
play(gameName){
console.log('我最喜欢玩' + gameName);
}
};
var student = new Student("007", "张三", 18, "男", "王者");
console.log(student);
student.play();
其中的play方法,通过打印也能够看到是出现在原型中的,只不过通过ES6写出来的,看起来更简洁,更符合学过强类型语言的规则,但是本质上是一样的