Home java Java Inheritance and Private

Java Inheritance and Private

Author

Date

Category

There are 2 classes, class and class
Classa.java- & gt;

package com.company;
  Public Class Classa {
    Private int x;
    Private int y;
    Public Classa () {
      x = 0;
      y = 0;
    }
    Public Classa (int x1, int y1) {
      x = x1;
      y = y1;
    }
    Public Void Print () {
      System.out.print (X + "" + Y + ");
    }
    Public String Tostring () {
      RETURN X + "" + Y + "";
    }
    Public Void Set (int x1, int y1) {
      x = x1;
      y = y1;
    }
  }

classb.java- & gt;

package com.company;
  Public Class Classb EXTENDS CLASSA {
    Private int z;
    Public Classb () {
      x = 0;
      y = 0;
      z = 0;
    }
    Public Classb (int x1, int y1, int z1) {
      x = x1;
      y = y1;
      z = z1;
    }
    Public Void Print () {
      System.out.printLN (X + "" + Y + "" + Z);
    }
    Public String Tostring () {
      RETURN X + "" + Y + "" + Z;
    }
    Public Void Set (int x1, int y1, int z1) {
      x = x1;
      y = y1;
      z = z1;
    }
  }

On the class A there are 2 variables with a Private modifier. Class B inherits class A, if it is possible to gain access to variables with a private modifier that is variables of class A. (if compiled in this form it gives an error that class b no Can use variables from mod. Private which is variables class A)


Answer 1

For access to child classes, the PROTECTED modifier is used.

In general, you can rewrite everything using X and Y:

Public Class Classb EXTENDS CLASSA {
  Private int z;
  Public Classb () {
    Super ();
    z = 0;
  }
  Public Classb (int x1, int y1) {
    Super (x1, y1);
    z = 0;
  }
  Public Classb (int x1, int y1, int z1) {
    Super (x1, y1);
    z = z1;
  }
  Public Void Print () {
    super.print ();
    System.out.printLN (Z);
  }
  Public String Tostring () {
    Return super.tostring () + z;
  }
  Public Void Set (int x1, int y1, int z1) {
    super.set (x1, y1);
    z = z1;
  }
}

It is better to rewrite the print () method so that it uses his Tostring ()


Answer 2

Variables Private work only in the classroom. Use Public or at all without access modifier.

If you need Save the values ​​of class A and use in class b , then add final

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions