Here's a question for Java class conversion!

Asked 2 years ago, Updated 2 years ago, 166 views

I am studying Java again, and I am posting a question because I have a question.

public class super{

    public int one= 11;
    public int two= 22;

    public void one_method() {
        System.out.println("super one_method");
    }

class subextends super{
    public int one = 1;
    public int two = 2;
    public int three = 3;
    public void one_method() {
        System.out.println("sub one_method");
    }

    public static void main(String[] args) {
        super mSuper = new sub();  // (=) mSuper = (super)new sub();
        System.out.println(mSuper.one);

    }

I did it. Super Class = (Super Class) has been transformed into a subclass.

I have a question here. When mSuper.one_method(); is run, one_method() of the subclass is overridden and used.

However, if the variable is pulled out, the one variable value (11) of super will be obtained instead of the one variable (1) of sub.

In class type conversion, the method is overridden if the name is the same, but why is the variable not allowed to be? I'm curious about the reason.

java class casting

2022-09-22 18:24

2 Answers

The questioner seems to be learning about object orientation.

Overriding is a redefinition of a function.

For example, if there is a class called car, Properties can be color, weight, etc., and functions can be start, stop, etc. That is, color and weight can be defined as starting with variables, and stopping with methods.

Let's think about the class design of cars and buses. Both cars and buses are cars, so you inherit the car. However, passenger cars are usually automatic for gasoline, while buses are manual for diesel. The function "start" should be implemented differently.

Overriding occurs when the function (method) needs to be changed.

Attributes are usually defined as variables, and attributes, such as color and weight, are common attributes for all cars, and the necessary attributes for a passenger car can be added to the passenger car.

This means that the property is added, not overridden.


2022-09-22 18:24

I'll explain about over-riding http://aroundck.tistory.com/2206 [King Pig Playground]

If you look here, the override is based on the method.

In other words, int one and two are not overlaid methods

Returns the default data types you have: 11 and 22.

If:::: System.out.println(mSuper.three);

If you do, you can't print it out because the supermarket doesn't have a parameter of three.

Overriding is based on the method.


2022-09-22 18:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.