(Object-oriented) Questions about object creation

Asked 2 years ago, Updated 2 years ago, 28 views

public class A {

    private double[] data;

    public A(double[] data) {
        this.data = data;
    }

    public double mean() {
            return null;
        }
}


public class B extends A{

    private String title;

    public B(double[] data) {
        super(data);
    }
    public String history() {
        return null;
    }
}

There are classes A and B. In this case, I would like to know why you are creating an object, such as A sample = new B(); .

저렇게 생성하면 B클래스의 history()메소드는 사용이 불가하고 A클래스에서 상속받은 mean()메소드만 사용이 가능하다고 배웠는데 그렇다면 A sample = new A();와 다를 것이 없지 않습니까?

Also, I would like to know the difference between A sample = new B(); and B sample = new B();.

I learned that the former is a method for versatility and diversity, so if it is correct, please give me an example, and if it is wrong, I would appreciate it if you could tell me why.

java

2022-09-22 20:18

1 Answers

I thought the same thing at first. The idea of object orientation is still difficult. There may be doubts that you have to inherit the code that has the complexity of the amount you wrote. Inheritance (object orientation) is ultimately for efficiency in system expansion.

First of all, one of the important characteristics of object orientation is All objects belonging to a particular type can receive the same message. You can understand that the act of sending a message is the concept of calling an object's method.

I think it's going to be too long, so I'll replace it with a code.

For a simple example with the code below,

The Weapon class was designated as a base type, and the remaining classes have redefined the attack method of the inherited Weapon class.

메인 메서드의 attackSomething()은 베이스타입인 Weapon을 파미터로 지정함으로서 Weapon 클래스로부터 파생된 클래스의 객체를 모두 받아들일 수 있습니다. (여기서 다형성 개념이 나옵니다.)

This allows you to create a new weapon class without modification of the existing code, even if additional weapons requirements arise.

I hope it's an answer to what you were curious about.

class CodeRunner{
    public static void main(String[] args){
        attackSomething(new Knife());
        attackSomething(new Gun());
    }

    static void attackSomething(Weapon weapon) {
        weapon.attack();
    }
}

abstract class Weapon {
    abstract void attack();
}

class Knife extends Weapon {
    void attack() {
        System.out.println ("knife attack");
    }
}

class Gun extends Weapon {
    void attack() {
        System.out.println ("gun attack");
    }
}


2022-09-22 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.