Thừa kế trong JAVA

em có đoạn code này:
‘’’

class Shape{
    public void draw(){
        System.out.println("Drawing a shape");
    }
}
class Retangle extends Shape{
    private int dai, rong;
    public Retangle(){
        dai = 1;
        rong = 1;
    }
    public void setX(int dai){
        if(dai > 0 && dai < 16)
            this.dai = dai;
        else if(dai <= 0)
            this.dai = 1;
        else
            this.dai = 15;
    }
    public int getX(){
        return dai;
    }
    public void setY(int rong){
        if(rong > 0 && rong < 16)
            this.rong = rong;
        else if(rong <= 0)
            this.rong = 1;
        else
            this.rong = 15;
    }
    public int getY(){
        return rong;
    }
    public void draw(){
        for(int i = 0; i < rong; i++){
            for(int j = 0; j < dai; j++){
                if(i == 0 || i == rong - 1)
                    System.out.print("*");
                else{
                    if(j == 0 || j == dai - 1)
                        System.out.print("*");
                    else
                        System.out.print(" ");
                }
            }
            System.out.print("\n");
        }
    }
}
class RightTrangle extends Shape{
    private int cVuong;
    public RightTrangle(){
        cVuong = 1;
    }
    public void setCVuong(int cVuong){
        if(cVuong > 0 && cVuong < 21)
            this.cVuong = cVuong;
        else if(cVuong <= 0)
            this.cVuong = 1;
        else
            this.cVuong = 20;
    }
    public int getCVuong(){
        return cVuong;
    }
    public void draw(){
        for(int i = 0; i < cVuong; i++){
            for(int j = 0; j <= i; j++)
                System.out.print("*");
            System.out.print("\n");
        }       
    }
}
class Artist{
    public void drawShape(Shape v){
        v.draw();
    }
}

public class BT3_10 {
    public static void main(String[] args) {
       Shape v = new Retangle();
       v.setX(); // error.
       
       
    }   
}

‘’’
tại sao dòng v.setX(); lại error ạ??? mong mọi người giúp…

Shape không có phương thức setX() dù đã được up casting sang Retangle nhưng v vẫn chỉ có thể gọi được các phương thức của Shape

1 Like

Em đang làm theo dạng đa kế thừa trong Java phải không ?
Xem link dưới.

cảm ơn anh nhiều… giờ em mới biết nó là up casting :sweat_smile: em tìm tài liệu về up casting đọc cho hiểu hơn… :grinning:

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?