Search code examples
javainheritanceextend

Syntax error with an extend in Java


This is my main.

package oleg;

import java.util.Scanner;

public class main_class {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int length,shetach,num;

        zura[] z1 = new zura[5];    

        for(int i=0;i<z1.length;i++)
        {
            System.out.println("Enter 1,2,or 3");
            Scanner s1=new Scanner(System.in);
            num = s1.nextInt();
            switch (num) {
                case 1:

                    z1[i] = new ribua();
                System.out.println("Enter length");
                length=s1.nextInt();
                z1[i].set_info();
                z1[i].shetach(length);
                System.out.println(shetach);    ////// here is the error

                break;

                default:
               System.out.println("error 3");
                   break;
            }
        }
    }

This is my first class from which I inherit.

package oleg;

public class zura {

    public int shetach(int shetach)
    {
        return shetach;
    }

    public void heikef()
    {

    }

    public void set_info()
    {

    }
}

This is my second class that extands the zura class

package oleg;

public class ribua extends zura {

    int length;

    public int shetach(int shetach)
    {
        shetach=length*length;
        return shetach;
    }

    public void set_info(int length)
    {
        this.length=length;
    }

My problem is in the main class in the row System.out.println(shetach); How am I printing the shetach?


Solution

  • When you pass a variable to a method it is copied. This means if you set that variable in the method it has no effect on the caller. i.e. it doesn't initialise the callers copy of the variable. You need to change your code to look like this.

    shetatch = z1[i].shetach(length);
    

    The variable shetatch inside the method has the same name. but otherwise nothing in common.