Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Inheritance gives you common API and common base type not the data.</p> <p>Add copy constructor which takes "A" argument and then copy properties from passed "A" object. Something like this:</p> <pre><code>package com.example; import java.io.IOException; import java.util.Scanner; class A { int a[]; int no; A() { } void init() { System.out.println("Number of elements for an array : "); Scanner in1 = new Scanner(System.in); no = in1.nextInt(); a = new int[no]; for (int i = 0; i &lt; no; i++) { System.out.println("Enter elements : "); Scanner in2 = new Scanner(System.in); a[i] = in2.nextInt(); } } void sort() { int tmp; for (int i = 0; i &lt; no - 1; i++) { for (int j = i + 1; j &lt; no; j++) { System.out.println("a[i] : " + a[i] + " a[i+1] : " + a[i + 1]); if (a[i] &gt; a[j]) { tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } } } void display() { System.out.println(); for (int i = 0; i &lt; no; i++) { System.out.println(a[i]); } } } class B extends A { B(A obj) { no = obj.no; a = new int[obj.a.length]; System.arraycopy( obj.a, 0, a, 0, obj.a.length ); } int tot = 0; float mean; void get_mean() { System.out.println("no : " + no); for (int i = 0; i &lt; no; i++) { tot += a[i]; } System.out.println("tot : " + tot); mean = (float) tot / no; System.out.println("mean : " + mean); } } class C extends A { C(A obj) { no = obj.no; a = new int[obj.a.length]; System.arraycopy( obj.a, 0, a, 0, obj.a.length ); } void median() { float median; if (no % 2 == 0) { int middle = no / 2; median = ((a[middle] + a[middle / 2]) / 2); } else { median = a[(no / 2)]; } System.out.println("median : " + median); } } public class Test { public static void main(String arg[]) throws IOException { A objA = new A(); objA.init(); B obj1 = new B(objA); obj1.get_mean(); C obj2 = new C(objA); obj2.sort(); obj2.median(); } } </code></pre> <p>But better approach is to use composition rather than inheritance. Just let your A class collect data and then inject this "data" object to B, C. B and C dont need to be "IS-A" objects. They should be "HAS-A" objects.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload