Study Case

Bikin class Person dengan atribut dasar:

  • name

  • age

Bikin subclass Programmer dan Student dan berikat atribut tambahan:

  • skills di class Programmer

  • scores di class Student

Manfaatkan konsep Inheritance dan Encapsulation

Task

// Inheritance
class Person {
    constructor(name,age) {
        this.name = name;
        this.age = age;
    }
}
class Programmer extends Person{
    constructor(name,age, skills) {
        super(name,age);
        this.skills = skills;
    }
}
class Student extends Person{
    constructor(name,age, scores) {
        super(name,age);
        this.scores = scores;
    }
}

let person = new Person("rajif",25);
let programmer = new Programmer("Candra", 21,["JS"])
let student = new Student("Bayu", 18, [80])
// console.log(person)
console.log(programmer)
console.log(student)



// encapsulation
class Person {
    constructor(name,age) {
        this._name = name;
        this._age = age;
    }
    get name(){
        return this._name;
    }
    get age(){
        return this._age;
    }
    set setName(name){
        this._name =  name;
    }
    set setAge(age){
        this._age = age;
    }
}
class Programmer extends Person{
    constructor(name,age, skills) {
        super(name,age);
        this._skills = skills;
    }
    get skills() {
        return this._skills;
    }
    set setSkills(skills){
        this._skills = skills;
    }
}
class Student extends Person{
    constructor(name,age, scores) {
        super(name,age);
        this._scores = scores;
    }
    get scores(){
        return this._scores;
    }
    set setScores(scores) {
        this._scores = scores;
    }
}

let person = new Person("rajif",25);
let programmer = new Programmer("Candra", 21,["JS"])
let student = new Student("Bayu", 18, [80])
// console.log(person)
console.log(programmer.name)
console.log(student.age)

Last updated

Was this helpful?