Call a method from another class(not main class) - java

How to call distanceTo(Point p) of Point.java into Point2.java under a method takes no parameter? There should be a way but I cannot find from my materials. Could anybody help me? It has been doing 2 days. Please help...
---------------------Point.java---------------------------------
public class Point{
private int x;
private int y;
//x and y coordinates as parameters
public Point(int x, int y){
this.x = x;
this.y = y;
}
//I want to call this method by calling a method which taken no parameter in Point2.java.
public double distanceTo(Point p){
return Math.sqrt(((x - p.x) * (x - p.x)) + ((y - p.y) * (y - p.y)));
}
}
---------------------ClonePoint.java---------------------------------
public class ClonePoint{
private int a;
private int b;
//x and y coordinates as parameters
public ClonePoint(int a, int b){
this.a = a;
this.b = b;
}
//I failed with this way. Can anybody correct me?
public double measureDistance(){//it should be takes no parameter.
return distanceTo(ClonePoint p)
}
}
----------------------PointDriver.java-----------------------------
public class PointDriver {
public static void main(String [] args) {
Point2 nn = new Point2(11, 22);
Point2 mm = new Point2(33, 44);
System.out.println(nn.distanceTo(mm)); //I succeeded with this!
System.out.println(nn.measureDistance(mm)); //But I got an error illegal start of expression
}
}

#Evan a class is a generalized container for your things. A car, a person, a point (in your case).
Everytime you want to "create" one or more object of your defined class, you instantiate them:
Person evan = new Person();
Person rob = new Person();
both of us are person, you don't really need to define class Person1 and Person2!
And in a class you should define the methods used to "relate" to other similar objects.
For example:
// In Person.java
public void greet(Person p) {
System.out.println("My name is "+this.name+". Nice to meet you +"p.getName());
}
// In main
rob.greet(evan); // it now gives compile errors of course but take the point :P
What you want to achieve is to create a better and more complete Point class with all the methods you want to use. In the end, just initialize more Point objects (same class!) in your main and play with them.
Hope it helps :)
EDIT
Ok, perhaps I've got what your homework wants you to perform.
A "parameter-less" method measureDistance() should make you wonder one important thing: "distance FROM which point????".
Obviously, if the function takes no parameters all the information needed to that calculus must be in the object which calls it. Don't you think?
So, you probably want to achieve a secondary class (if you really need to define it as Point2 it's ok, but change that name because it's confusing) which can take a Point in its constructor (saving this information in itself) and then use that Point to measure distance from it.
Example
public class Point2{
private int a;
private int b;
private Point startingPoint;
public Point2(int a, int b, Point p){
this.a = a;
this.b = b;
startingPoint = p;
}
// Computes the distance from starting point to this
public double measureDistance(){//it takes no parameter.
return startingPoint.distanceTo(a, b);
}
/*
if you can't edit distanceTo() it gets a little verbose but you must create a
Point with Point2 coordinates - remember this example when you will study Inheritance
public double measureDistance() {
Point endingPoint = new Point(a, b);
return startingPoint.distanceTo(endingPoint);
}
*/
}

First, it is not good idea to duplicate a class that does the same thing because you are doing extra unneeded work. Second, if you make various point types, you are loosing the advantage of seamless compatibility between them.
Then, if you want to call method from other class you can do it like this:
NameOfOtherClass.SomeMethod()
But you have to declare the SomeMethod in the other class as static...
public static double SomeMethod() { ... };
But then you can't use the method to access the data of your concrete points you have created in your code, so any data should be put into parameters.
If you want to do it your way, you have to just add a parameter to public double measureDistance()
function so the function has access to another point to measure distance to.

Related

Building a "Wrapper" class in Java

I'm wondering if anyone knows a way to wrap an object inside another one in Java. So if we start with a class A, I essentially need to build a subclass (class B) that takes an instance of class A in the constructor and initialises all it's fields to be the same as those of class A. The idea is that B becomes A, but just adds some extra stuff to it. I'm wondering if there's any way to do this without having to manually assign all the fields (also it's impossible to assign final fields this way so that's another thing to consider).
This is my first question ever so I apologise if it's not clear. Please feel free to request clarification if required.
Thanks for any help,
Andrei
You cannot change final variables, and you'll have to change the other fields manually. You should really just create another object entirely.
public class A {
private final int x;
private int y;
public A( int x, int y ) {
this.x = x;
this.y = y;
}
...
}
public class B extends A {
public B( final A a ) {
super( a.getX(), a.getY() );
}
...
}

Overriding methods in java using super

So, I have to create 68 different summing methods using the datatypes, int, float, double and short. The class is called, OverloadingSums. Here is an example of one the methods.
public double sum(double x, float y, int z)
{
return x+y+z;
}
Now I'm being asked to create a class called ZeroSum, essentially copying OverloadingSum and returning everything to zero. Here is an example.
public double sum(double x, float y, int z)
{
return 0;
}
Then I'm being asked to create another class called RealSum, which will extend the ZeroSum class. I'm a little confused about the wording of this assignment, not sure if the stackoverflow community could help but I'm just extremly confused.
Here is the assignment requirements:
Now that we have thoroughly explored overloading we are going to
explore overriding. Create a class called ZeroSum.java. Take all of
the methods from OverloadingSum.java and change them to return all
zeros in ZeroSum.java. Next, create a class called RealSum.java. This
class, RealSum, will extend the ZeroSum class. Having all zeros for
our sums isn't very useful. We will need to override the parent, or
super class methods to produce real results. Create the necessary
methods to override all of those in the ZeroSum.java. When you are
done run your classes against DrivingSum.java.
This is what I have in my main method:
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
RealSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) );
System.out.println("Calling ZeroSum " + real.sum(x,y) );
}
}
So, from how I'm understanding this I wrote the following code:
public class ZeroSum extends RealSum{
public double sum(double x, float y, int z)
{
return super.sum(x,y,z);
}
This will grab the method from RealSum, instead of using the sum method located in the ZeroSum class. So when I run the main method, zero.sum(x,y) gives me 30.
The confusion comes from the fact that the assignment asks me to set everything in ZeroSum returning to zero. If I extend ZeroSum to RealSum, it doesn't really make a difference. Am I doing this correctly? or Am I just overthinking this way too much?
The goal of this assignment is to explore overriding concept, where function executed depends on type of object it called upon on run time, so you will have something like this :
public class ZeroSum {
public double sum(double x, float y)
{
return 0;
}
}
public class RealSum extends ZeroSum{
public double sum(double x, float y)
{
return x+y;
}
}
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
ZeroSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) ); //here the sum will return zero
System.out.println("Calling ZeroSum " + real.sum(x,y) ); //here the sum will return 30
}
I believe he's trying to make a point in which whatever you write in the parent class is transferred (this is called inheritage) to the child. You can override this by writing a method in the child class using the same name and arguments as the parent class' method.
I also believe you read the assignment a bit wrong, it said:
This class, RealSum, will extend the ZeroSum class.
I interpret this as RealSum is the child to ZeroSum, not the other way around as such:
public class RealSum extends ZeroSum{
//code code code
}
This means everything in ZeroSum is set to 0 and RealSum set new values, not using the super. I'm not betting my hand this is correct but try to read the assignment again after a break and some fresh air :)
Hope this helps!

Java newbie: How to assign current state of object to another, without establishing reference?

Once again, I'm looking for a way to bypass this array problem, how? Is there any way other than clone()?
I'm asking because fighting with clone(), protection and implemention stuff didn't work for me...
//assuming you have proper class and constructor (point(int x, int y))
/*
point 7POINTSARRAY[]=new point[7];
for(int i=0;i<7;i++)
{
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
}
//This won't work, so...
*/
point B = new point(0,0); // You need this.
for(int i=0;i<7;i++){
7POINTSARRAY[i]=B; // And this.
//But I want to read and assign value only,
// not establish a reference, so it can work How?
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x);
Though desired output is A[1].x=1, it's been owerwritten several times, and now A[1].x = 7.
You need to a create a new point for every element of the array if you want them all to reference different objects:
for(int i=0;i<7;i++)
{
point B = new point(0,0); // Put this *inside* the loop
7POINTSARRAY[i]=B; // Now B is a new instance of point
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x); // should now print 1
I haven't changed your code formatting but improving that will make the above clearer and easier to understand.
Sorry but Java works only with references for complex objects. You should use and implement clone() correctly this can't be the problem. clone() is well defined approach.
Typical clone for first level class looks like following
#Override
public Object clone() {
try {
A ans = (A) super.clone();
// do complex stuff
return ans;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
the line
A ans = (A) super.clone();
does default clone, which includes cloning object but not it's members. You should cascade clone for members. Since clone() is a member, it has access to protected members of the parent.
If your parent is Cloneable you should write
#Override
public Object clone() {
A ans = (A) super.clone();
// do complex stuff
return ans;
}
because parent can't throw exception.
For example, if you have point class looking like follows
class point {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
then you should just fix it in the following way
class point implements Cloneable {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
to make it cloneable.
Then you will be able to write
point a = new point(1,2);
point b = (point) a.clone();
and you will get 2 separate copies.
the problem is with the line
7POINTSARRAY[i]=B
which means that each object in 7POINTSARRAY refer (or points) to the same object B.
so when you do inside the loop
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
you actually always changing B.
You should do instead:
for(int i=0;i<7;i++){
7POINTSARRAY[i] = new point(i,i);
}

How to share data between separate classes in Java

What is the best way to share data between separate classes in Java? I have a bunch of variables that are used by different classes in separate files in different ways.
Let me try to illustrate a simplified version of my problem:
This was my code before:
public class Top_Level_Class(){
int x, y;
// gets user input which changes x, y;
public void main(){
int p, q, r, s;
// compute p, q, r, s
doA(p,q,r);
doB(q,r,s);
}
public void doA(int p, int q, int r){
// do something that requires x,y and p, q, r
}
public void doB(int q, int r, int s){
// does something else that requires x, y and q, r, s
}
}
Now it looks something like this:
public class Top_Level_Class(){
int x, y;
SomeClass1a a = new SomeClass1a();
SomeClass1a b = new SomeClass1b();
// gets user input which changes x, y;
public void main(){
int p, q, r, s;
// compute p, q, r, s
a.doA(p,q,r);
b.doB(q,r,s);
}
public class SomeClass1a() { // in its own separate file
public void doA(int p, int q, int r){
// do something that requires x,y and p, q, r
}
}
public class SomeClass1b() { // in its own separate file
public void doB(int q, int r, int s){
// does something else that requires x, y and q, r, s
}
}
So anyway, should I pass x and y each time (where x,y are variables stored in the helper class func) ?
a.set(x,y);
a.doA(p,q,r);
My idea was to have a special container class where x and y are held. The top level class would have an instance of the container class and change x,y using the set methods.
// in the top level class:
Container c = new Container(x,y);
a.setContainer(c);
b.setContainer(c);
My helper classes would also have an instance of the container and it would point to the same instance as in the top level. That way they access the same x,y as in the top level.
I would like to know if I should
Use the container class
Load x,y each time into the subclasses
?? Some better method ??
I guess the answer to your question is the Design Pattern called Singleton.
It basically allows you to get and exploits the same (and unique) instance of a class whenever you want in your system.
This is its implementation (please forgive possible syntax errors, I did not compile it):
class Container{
//eventually provides setters and getters
public float x;
public float y;
//------------
private static Container instance = null;
private void Container(){
}
public static Container getInstance(){
if(instance==null){
instance = new Container();
}
return instance;
}
}
then if elsewhere in your code you import the Container you can write for example
Container.getInstance().x = 3;
temp = Container.getInstance().x;
and you will affect the attributes of the unique container instance you have in your system
In many cases it is however better to use the Dependency Injection pattern as it reduces the coupling between different components.
I am having a hard time seeing what your problem is -- why don't you want to pass x an y as a parameter?
Oh, well. Assuming you don't, I don't see a need for a new container class. Do it this way:
public class SubClass1a() { // in its own separate file
public void doA(Top_Level_Class caller, int p, int q, int r){
// do something that requires x,y and p, q, r
// **to get x use the expression term caller.getX() and caller.getY()**
}
}
Of course you need to add the public getter methods getX() and getY() to Top_Level_Class.
If you do not want SubClass1a to be dependent on Top_Level_Class then you could create an interface that provides access to the variables.
Blockquote
The main reason I didn't want to pass x,y each time is because I have several functions in several SubClasses that each use (x,y, z, etc) and it didnt seem right to pass in like 6-8 variables each time I call a function. The sub classes used to be dependent, but I'm trying to take them out of the file so they can be used in a different project.
Blockquote
If this is the case then you are better off abstracting your variables out to a container class. If every instance of these no-longer-dependent classes is going to use a large subset of these variables then it makes sense to have them all in one instance. Variables that are logically related should be found in the same place. Your approach should be something like:
public class Top_Level_Class(){
Container container = new Container(x, y, p, q, r, s);
SubClass1a a = new SubClass1a(container);
SubClass1a b = new SubClass1b(container);
// gets user input which changes x, y using container's getters and setters
public void main(){
// compute and set p, q, r, s
a.doA();
b.doB();
}
public class SubClass1a(Container c) { // in its own separate file
public void doA(c.getX, c.getY, c.getP, c.getQ, c.getR){
// do something that requires x, y, p, q, and r
}
}
public class SubClass1b(Container c) { // in its own separate file
public void doB(c.getX, c.getY, c.getQ, c.getR, c.getS){
// does something else that requires x, y, q, r, and s
}
}
public class Container(x, y, p, q, r, s) {
//getters and setters for all variables
}
This keeps you from getting into a variable passing spaghetti-code situation, and when you want to use just one or two of these classes later your code is modular enough to port with just those classes and your container.
This question is a bit mad - the code in the question won't compile.
public class Main {
public static void main(String... args) {
MutableDataContainer m = new MutableDataContainer();
ImmutableDataContainer i = computeImmutableData();
new ADoer().doA(m, i);
new BDoer().doB(m, i);
}
...
}
class MutableDataContainer {
private int x, y;
... // getters and setters below
}
class ImmutableDataContainer {
private final int p, q, r, s;
... // getters below
}
You'll need to define ADoer and BDoer as well.

Super class reference to a sub class object?

Give me a situation where we need to use the super class reference to a subclass object in Java.Please give me a real time example.
Thx
I know this is old but this cropped up on a project I've been working on recently (just a junior developer doing something unexpected - there was no actual reason for it!) and I think some of the answers have missed the point..
This has nothing to do with normal polymorphism; I think the question relates to the case where the code looks like this:
class A {
B b; //odd reference here..
}
class B extends A {
}
Where the sub-class is used in the definition of the super-class. As far a I can tell there is no legitimate reason for coding something like this yourself, however the reason the language allows you to do this is that it's required for some of the core Java classes e.g. Object.
For example, although it doesn't store a reference to it, the code for Object creates and returns a String object in it's default toString method, however, String is a sub-class of Object.
It's interesting to note that although it's technically allowed, it doesn't make sense to have a superclass create a subclass instance in its constructor.
e.g.
class A {
B b;
A(){
b = new B();
}
}
class B extends A {
}
This will just crash due to the fact that it creates an infinite loop, since B's constructor is calling A's constructor, which is calling B's constructor etc..
To Take Full Advantage of polymorphism...You have to understand polymorphism fully for you to really appreciate this... You can actually achieve the same behavior using an Interface as appropriate, so they say...
abstract class Shape {
abstract double getArea();
}
class Rectangle extends Shape{
double h, w;
public Rectangle(double h, double w){
this.h = h;
this.w = w;
}
public double getArea(){
return h*w;
}
}
class Circle extends Shape{
double radius;
public Circle(double radius){
this.radius = radius;
}
public double getArea(){
return Math.PI * Math.sqrt(radius);
}
}
class Triangle extends Shape{
double b, h;
public Triangle(double b, double h){
this.b = b;
this.h = h;
}
public double getArea(){
return (b*h)/2;
}
}
public class ShapeT{
public static void main(String args[]){
//USAGE
//Without polymorphism
Triangle t = new Triangle(3, 2);
Circle c = new Circle(3);
Rectangle r = new Rectangle(2,3);
System.out.println(t.getArea());
System.out.println(c.getArea());
System.out.println(r.getArea());
//USAGE with Polymorphism
Shape s[] = new Shape[3];
s[0] = new Triangle(3, 2);
s[1] = new Circle(3);;
s[2] = new Rectangle(2,3);
for(Shape shape:s){
System.out.println(shape.getArea());
}
}
}
I hope I'm not wrong on this... just a thought!
That question doesn't seem quite right ... putting an explicit reference to a child-class in the parent-class seems like an intent to break the hierarchy and the library.
As soon as the parent-class starts to carry a reference to the child-class, the parent-class is dependant upon knowing it's descendants; that is bad.
Unless the question was misquoted here, I'd say your interviewer was talking through his hat.
class Person
String hairColor = "default_noColor";
-----------------------------
class German extends Person
String hairColor = "brown";
-----------------------------
class Scandinavian extends Person
String hairColor = "red";
-----------------------------
public static void main(String args[]) {
Person p = new Person();
German g = new German();
Scandinavian s = new Scandinavian();
sysout p.hairColor // prints default_noColor
if (cond1) {
p = g;
}
sysout p.hairColor // prints brown
else if (cond2) {
p = s;
}
sysout p.hairColor // prints red
}
now, if germans start having black hair, i recompile class German and the main() is totally agnostic of how the German has changed. The main method continues to work as if nothing ever happened and prints black.
Kindly excuse minimal grammar and syntax
Using this kind of assignment you can not call the overloaded method in the subclass which is not in super class.
public class Reference {
public static void main(String args[]){
A a = new B();
//B b = new A(); // You can not do this, compilation error
a.msg(); // calls the subclass method
((B)a).msg("Custom Message"); // You have to type cast to call this
System.out.println(a.getClass());
if(a instanceof B){//true
System.out.println("a is instance of B");
}
if(a instanceof A){//true
System.out.println("a is instance of A also");
}
}
}
class A{
public void msg(){
System.out.println("Message from A");
}
}
class B extends A{
public void msg(){//override
System.out.println("Message from B");
}
public void msg(String msg){//overload
System.out.println(msg);
}
}
Uh, any time? If you have something like a polymorphic linked list:
class Node {
has 'next' => ( isa => 'Node' );
}
class TextNode extends Node {
has 'text' => ( isa => 'Str' );
}
class ImageNode extends Node {
has 'image' => ( isa => 'Image' );
}
Then you can do:
TextNode->new(
text => 'Here is my cat:',
next => ImageNode->new(
image => 'nibbler.jpg',
next => undef,
),
);
Your specific situation involves Node holding a reference to TextNode or ImageNode, which is probably fine in Java:
Node->new( next => TextNode->new ( ... ) )
Though I would make Node a role in languages with that feature... the idea is largely the same.
The Liskov substitution principle states that subclasses should behave exactly like their superclasses, so you can substitute a subclass anywhere the superclass is used.
Here's an important and most instructive example: java.lang.reflect.Array:
The Array class provides static methods to dynamically create and access Java arrays.
getLength(Object array)
Returns the length of the specified array object, as an int.
get(Object array, int index)
Returns the value of the indexed component in the specified array object.
set(Object array, int index, Object value)
Sets the value of the indexed component of the specified array object to the specified new value.
Arrays are passed around as Object, which is the superclass of all array types. It's necessary because we're doing reflection: we don't always know what the array type will be at compile time.
It's really rather odd because the type of situation where it might be useful (supplying a custom implementation of a singleton object for instance) has better alternatives to that; in particular the service loader mechanism.
And outside the world of globals in disguise you do tend to run into issues with circular references. (Consider that the super reference within your sub-class field points to the enclosing super instance which in turn is a reference from within the sub-class ...)
I think this can happen if the class and its subclass share child parent relationship of some sort and the child has a reference to its parent, something like this
public interface Node
{
String getName();
int getValue();
Container getParentContainer();
}
public interface Container extends Node
{
Set<Node> getChildren();
}
I would be interested to see how this can be designed in a better way to resolve this.

Categories