I have an ArrayClass and mergeSortArray extends it. And mergeSortArray contains a mergeSort() method. However, since I used super to call a constructor from the superclass, I do not know how to refer to the mergeSortArray (the subclass object / array) and pass it as a parameter in the mergeSort method. In fact, is this even feasible ? I know I can do this in a NON- OOP way. However, I am keen to know how to do this in an OOP way.
Please correct me if I have said incorrect, as I am new to Java and I want to learn more about it.
// ArrayClass Object
import java.util.*;
import java.io.*;
import java.math.*;
public class ArrayClass{
public int[] input_array;
public int nElems;
public ArrayClass(int max){
input_array = new int [max];
nElems = 0;
}
public void insert(int value){
input_array[nElems++] = value;
}
public void display(){
for(int j = 0; j < nElems; j++){
System.out.print(input_array[j] + " ");
}
System.out.println("");
}
}
import java.io.*;
import java.util.*;
import java.math.*;
class mergeSortArray extends ArrayClass{
public mergeSortArray(int max){
super(max);
}
public void methodOne(){
int[] output_array = new int[super.nElems];
mergeSort( // ************* // ,output_array,0, super.nElems -1);
}
................
}
I am not sure what I should put to replace ****** such that I can pass mergeSortArray as a parameter into the mergeSort method.
There isn't a mergeSortArray. You inherit input_array like (and no need for super.nElems you inherit that too),
mergeSort( input_array, output_array, 0, nElems - 1);
Your sub-class will inherit everything that is protected or greater visibility (not private), however your ArrayClass gives you both public fields
public int[] input_array;
public int nElems;
They should probably be protected and have accessor methods (getters).
protected int[] input_array;
protected int nElems;
public int size() {
return nElems;
}
public int[] getInputArray() {
return input_array;
}
First of all, I suggest you not to have public fields on OO code. You got two public fields (input_array and nElems), you should change them to private and create acessors if you need.
Then, to refer to those fields on the subclass, you can either use a protected acessor if you wish to hide the acessor from the rest of the API or a public one, if it's part of your public API. That way, on your ArrayClass:
public class ArrayClass {
private int[] input_array;
private int nElems;
//this may be public
protected int[] getInputArray() {
return input_array;
}
and when you get to call your mergeSort method, you can use getInputArray()
Related
import java.util.ArrayList;
public class Example {
public static abstract class item{
public static abstract int getID(String s);//<<< the problem
public abstract String doThingsWithID(int i);
}
public static class SpecificItem extends item{
int positive;
int negative;
public SpecificItem(int p,int n){
this.positive=p;
this.negative=n;
}
protected enum IDHelper{
POSITIVE(0),NEGATIVE(1);
final int i;
IDHelper(int i){this.i=i;}
}
public static int getID(String s){
return IDHelper.valueOf(s).i;
}
public String doThingsWithID(int i){
switch(i){
case 0:
return "positive="+String.valueOf(positive);
case 1:
return "negative="+String.valueOf(negative);
default:
return "shouldn't happen";
}
}
}
public class Container<T extends item>{
public ArrayList<T> l;
public int ID;
public Container(ArrayList<T> l,String id){
this.l=l;
this.ID=T.getID(id);
}
public void doThings(){
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i).doThingsWithID(ID));
}
}
}
public static void main(String[] args){
ArrayList<SpecificItem> l = new ArrayList<>();
l.add(new SpecificItem(1, -1));
l.add(new SpecificItem(2, -2));
Example main=new Example();
Container<SpecificItem> cont=main.new Container<>(l, "POSITIVE");
cont.doThings();
}
}
I have a code similar to this one. I want to be able to pass String s into a Container and forget about it, meaning give the Container constructor String s and have it do the getID() on its own. However, it appears I am forced to try to mimic the getID() functionality of Container constructor from outside, basically having a Container(ArrayList<item> l, int id) and expecting to pass in SpecificItem.getID(String s) to id, which I would ideally like to avoid. Any help would be greatly appreciated.
Edit: I primarily want the functionality of being able to link specific names to cases - basically the functionality of an enum - thus minimizing the amount of work if I want to rename a case.
And for anyone wondering, I am willing to modify most of the classes and methods, as long as I can retain the aforementioned functionality and can minimize the amount of "stuff" I need to pass into the function.
Also, I think the best option I have is to pass in a dummy new SpecificItem() that the Container constructor can use to do the T.getID(), and just have getID not be static. It feels kinda hacky though, so many there is a better option.
I have a superclass and one subclass with some variables like below:
public class A{
private int first;
private int second;
public A(int _first, int _second){
first = _first;
second = _second;
}
public int getFirst(){
return first;
}
}
public class B extends A{
private int third;
public B(int _first, int _second, int _third){
super(_first, _second);
third = _third;
}
public int getThird(){
return third;
}
}
I want to build a method in the main class that accepts a generic argument that can be of type A or type B like below:
public class Main{
public int val = 2;
public static void main(String []args){
A a = new A(1, 2);
B b = new B(1, 2, 3);
printObject(a);
printObject(b);
}
public void printObject(A a){
int f = a.getFirst() * val;
int s = a.getSecond() * val;
if(a instanceOf B){
int t = a.getThird() * val; // compiler does not find the getThird() method this way
}
}
}
How can this be achieved?. is generics an option? I have thought about making printObject() method inside A then override it inside B however I have some other variable like val above that I am creating in main.
update
I tried to use instanceOf like the above method. But this way the compiler does not find the subclass's specific method.
Firstly, by definition, if you declare A as a parameter to any method and B is it's sub-class, then any A or B can be passed to that method.
You could then achieve what you want using the instanceof operator (to check if the parameter passed in is of type B). However, inheritance / method override should typically be used rather than instanceof.
You could pass 'val' into the printObject() methods on A/B. If several variables like 'val' are involved you could pass in another object or perhaps you need to split your code across multiple methods on class A (overridden in B), passing in different values as appropriate? (You wouldn't normally do calculations in a method whose purpose is to print an object but perhaps that was just an example?)
Everything is much simplier) You could get rid of this method in the main class, cause it's producing some redundant coupling. And all this instanceof really smells in 2019. You could make it more independent.
Class A:
public class A{
private int first;
private int second;
public A(int _first, int _second){
first = _first;
second = _second;
}
public int getFirst(){
return this.first;
}
public int getSecond(){
return this.second;
}
public void print(int multiplier) {
System.out.println(this.first * multiplier);
System.out.println(this.second * multiplier);
}
}
Class B:
public class B{
private int third;
public B(int _first, int _second, int _third){
super(_first, _second);
third = _third;
}
public int getThird(){
return this.third;
}
#Override
public void print(int multiplier) {
super.print(multiplier);
System.out.println(this.third * multiplier);
}
}
Class Main:
public class Main{
public int val = 2;
public static void main(String []args){
A a = new A(1, 2);
B b = new B(1, 2, 3);
a.print(val);
b.print(val);
}
}
Writing object oriented code is more than extending a class , your API's and other functionality should be designed as part of the solution.
In your case, the most appropriate way to do this is to add the print method to the object itself, you can either override the entire function or to call the super class inside the overriding class.
public class A{
/// ... your code
public void print(){
System.out.println("first :"+first+", second : "+second);
}
}
public class B extends A{
/// ... your code
public void print(){
//Option A - use parent class getters/setters to implement print for object B
System.out.println("first :"+super.getFirst()+", second : "+super.getsecond() +" third" + third);
}
//Option B (More usable to methods returning a value or performing an update) - Perform operation on parent variables, then perform on class specific variables
super.print()
System.out.println("third : "+third);
}
}
and then
A a = new A();
A b = new B();
a.print();
b.print();
Will each call the correct runtime function based on their actual implementation
I tried to override compareTo method however I see compiler uses Java.lang.Double.compareTo method instead of my compareTo.
What is wrong here and what should I fix and change so my own compareTo method will be used?
package GenerecEx;
import java.util.ArrayList;
import java.util.Collections;
public class ArraySort implements Comparable{
double val;
static ArrayList<Double> a=new ArrayList<Double>();
public static void main(String[] args) {
a.add(2.4);
a.add(8.4);
a.add(9.4);
a.add(4.4);
a.add(6.4);
sort(a);
printList(a);
}
public static void printList(ArrayList a1)
{
System.out.println(a1.toString());
}
static public void sort(ArrayList <Double> a1)
{
for (int i=0;i<a1.size();i++){
for(int j=0;j<a1.size()-i-1;j++){
if (a1.get(j).compareTo(a1.get(j+1))>0){
double temp = a1.get(j);
a1.set(j,a1.get(j+1) );
a1.set(j+1, temp);
}
}
}
}
#Override
public int compareTo(Object element)
{
if (this.val < (Double) element)
return -1;
else return 1;
}
}
Implementing the Comparable interface allows you to override the compareTo method on the implementing class. Having implemented Comparable on the ArraySort class, your compareTo method should actually be comparing objects of type ArraySort, not generic Objects cast as Double.
I'm trying to construct a subclass and I get error that the constructor is undefined?!?!
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LinearAlgebra
{
public class Matrix
{
public int m;
public int n;
public float Matrix[][];
void Matrix(int tempm, int tempn)
{
m = tempm;
n = tempn;
Matrix = new float[m-1][n-1];
}
}
public static void main(String[] args)
{
LinearAlgebra Geometry = new LinearAlgebra();
LinearAlgebra.Matrix Rotation = Geometry.new Matrix(3,3);
System.out.println("hello");
}
}
Sorry have been out of java for a while. I looked at some java tutorials and think I'm doing the same but it is not working
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
void Matrix(int tempm, int tempn)
This is a method not a constructor. You must remove the return type void:
Matrix(int tempm, int tempn)
You should also name your local variables to start with a lowercase, geometry instead of Geometry. Using an uppercase confuses the reader because it makes it seem as if the nested class Matrix is a static class, not an inner class. Same for the Rotation variable.
I have the following problem. Am trying to make a polymorphic call and the result would depend on the variable that changes value depending on the underlying class. Tried different things however it doesn't work. Please let me know what should be changed. Problem is that although c.w reads both the local variable w, which is defaulted to 0 and reads the one from appropriate class it always defaults to 0. Here is the code:
class Cycle{
private int w = 0;
public void move(){
System.out.println("Cycle moving");
}
public int wheels(Cycle c){
switch (c.w){
case 1: return 1;
case 2: return 2;
case 3: return 3;
default: return 0;
}
}
}
class Unicycle extends Cycle{
public int w = 1;
public void go(){
System.out.println("Unicycle go");
}
}
class Bicycle extends Cycle{
public int w = 2;
public void go(){
System.out.println("Bicycle go");
}
}
class Tricycle extends Cycle{
public int w = 3;
public void go(){
System.out.println("Tricycle go");
}
}
public class TestCycle {
public static void ride(Cycle c){
c.move();
int now = c.wheels(c);
System.out.println(now);
}
public static void main(String[] args){
Bicycle b = new Bicycle();
ride(b);
Unicycle u = new Unicycle();
ride(u);
Tricycle t = new Tricycle();
ride(t);
}
}
Your problem (well one of them) is that you are redefining the class variable 'w' in each of your subclasses. Define it one as a member of 'Cycle' and have each subclass set it correctly in their constructors.
class Cycle{
protected int w;
public void move(){
System.out.println("Cycle moving");
}
public int wheels(){
return w;
}
}
class Unicycle extends Cycle{
public Unicycle() {
w = 1;
}
public void go(){
System.out.println("Unicycle go");
}
}
Or you can define an abstract method called 'wheels()' in the superclass and override it in the subclasses. It's a matter of taste.
the wheels method should be more like
public int getWheelCount(){
return this.w;
}
You invoke it on the instance itself, you don't need to pass an argument. If the current instance is a Tricycle, the method will return 3, etc...
Since Cycle.w is private, it's not visible from its inheritors. This means that for example Tricycle.w it's not the "same" variable, and it's not visible in Cycle (that's why you always get 0). You have to make Cycle.w at least protected, then remove w from all subclasses, and set its value in each subclass's constructor to what you want.
It's probably not the answer you are looking for, but the following works. Please give more details on what you are trying to do.
public abstract class Cycle {
protected int nWheels;
protected String goText;
// no constructor.
public void go() {
System.out.println(goText);
}
public int wheels() {
return nWheels;
}
}
...
public class Unicycle extends Cycle {
public Unicycle() {
nWheels = 1;
goText = "Unicycle go";
}
}
Note that I made Cycle abstract because I don't want it to ever be instantiated.
EDIT:
public static int getNumberOfWheels(Cycle cycle) {
return cycle.wheels();
}
which is obviously not very useful since a simple call to cycle.wheels() would do the same as calling this function.
I'm not sure why you want to avoid constructors. Maybe you should write the exact question you are trying to answer.