How to call a public method WITHIN a private attribute? - java

I am new to Java. So the question may seem naive... But could you please help?
Say for example, I have a class as follows:
public class Human {
private float height;
private float weight;
private float hairLength;
private HairState hairTooLong = new HairState() {
#Override
public void cut(Human paramHuman) {
Human.this.decreaseHairLength();
}
#Override
public void notCut(Human paramHuman) {
Human.this.increaseHairLength();
}
};
public float increaseHairLength () {
hairLength += 10;
}
public float decreaseHairLength () {
hairLength -= 10;
}
private static abstract interface HairState {
public abstract void cut(Human paramHuman);
public abstract void notCut(Human paramHuman);
}
}
Then I have another class as follow:
public class Demo {
public static void main(String[] args) {
Human human1 = new Huamn();
Human.HairState.cut(human1);
}
}
The statement
Human.HairState.cut(human1);
is invalid...
I intend to call the public cut() function, which belongs to hairTooLong private attribute.
How should I do it?

Since HairState is private to Human, nothing outside the Human class can even know about it.
You can create a method in Human that relays the call to its private mechanism:
public class Human {
. . .
public float cutHair() {
return hairTooLong.cut(this);
}
}
and then call that from main():
System.out.println(human1.cutHair());

Two other solutions to previous comment:
You can implement a getter which returns the hairTooLong attribute.
You can invoke the the cut() method through the reflection API (but you don't want to go there if you are beginner).
Would suggest either the solution in the previous comment, or the first option presented here.
If you are curious, you can have a look to the reflection API and an example here: How do I invoke a Java method when given the method name as a string?

In java there are four access levels, default, private, public and protected. Visibility of private is only limited to a certain one class only (even subclass cannot access). You cannot call private members in any other class. Here is a basic details of java access levels.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
For more details check Oracle docs

Related

Accessing a particular instance of class inside the same class in java

I have a java code with the structure that is shown below:
public class x{
public static void main(string[] args)
{
ysample1 = new y(m)
ysample2 = new y(l)
....
}
}
public class y{
private int m_m
public y(int m)
{
m_m = m
}
public void control()
{
h h1 = new h(ysample2)
}
}
At some point when I want to call method control for ysample1 I may need to access ysample2 object.How can I define instance of class y global, so I can access ysample2 inside the control method in class y?
Does anyone know how can I fix this? Thanks.
You can't do what you want to do the way you wrote it.
I think you need to ridefine "control()" method like this:
public void control(Y ysample)
{
h h1 = new h(ysample)
}
So now you need to have an "ysample" as parameter and you can do from your main
control(ysample2);
and you will have what i understood from you question. If you need something else please comment.

Making a static duplicate of non-static integer

For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.

Java extending classes mess

I don't know what pot I was smoking when I posted the original, but I came to my senses and came up with this. I am not an experienced coder, but the entire post was made mostly as a question that for the most part has been answered. I now know classes can't have code directly in them, and more so about the core structure.
class Shape {
public static void ShapeAttemptTwo()
{
class Circle extends Shape
{
public static CircleAttemptTwo()
{
int pi = 3.14;
int r=4;
}
}
class Rectangle extends Shape
{
public static Rectangle()
{
int l = 14;
int b = 10;
int z = l*b;
}
}
class Square extends Shape
{
public static Square()
{
int a = 11;
System.out.println(a * a);
}
}
// Java code 7, invalid method declare, return type required. (public static //CircleAttemptTwo())
// I'm lost on this one, could I have some help?
// and reached end of file while parsing }, confusing to me.
/EDIT THANK YOU VERY MUCH. The constructive crit. really helped, as I ended up with a lot of knowledge and my final code was
class Shape {
public static void ShapeAttemptTwo()
{
class Circle extends Shape
{
public static CircleAttemptTwo()
{
int pi = 3.14;
int r=4;
}
}
class Rectangle extends Shape
{
public static Rectangle()
{
int l = 14;
int b = 10;
int z = l*b;
}
}
class Square extends Shape
{
public static Square()
{
int a = 11;
System.out.println(a * a);
}
}
You're doing several things wrong:
1) Your "static main()" belongs inside a class
2) You can only have one "public class" per module.
SUGGESTED CHANGE:
public abstract class Shape
{
public static void main(String[] args) {
Shape rectangle = new Rectangle (14, 10);
System.println ("rectangle's area=" + rectangle.getArea ());
...
}
}
class Circle extends Shape {
...
}
class Rectangle extends Shape {
int l;
int b;
public Rectangle (int l, int b) {
this.l = l;
this.b = b;
}
public int getArea () {
return l * b;
}
}
...
Aside from the errors Tomas pointed out:
5) You forgot the word class in the Square declaration.
6) You cannot declare a public class directly inside a method. Java does allow you to declare classes, called "local classes" inside methods. However, I'm not sure if that's what you really want to do; if you do, you can only use Circle inside your main method, so you're not really creating a hierarchy. Anyway, when you declare a local class, it can't have public, protected, or private keywords on it, so that explains the first error message you're seeing.
EDIT: Based on the second post: Every method has to have a return type; if you don't actually want the method to return anything, the return type should be void. Thus:
public static void CircleAttemptTwo()
{
//int pi = 3.14; should be
double pi = 3.14;
int r=4;
}
However, constructors don't need a return type, but they can't be static. So public Square() and public Rectangle() are OK. CircleAttemptTwo doesn't match the class name, so it isn't a constructor.
"reached end of file" usually means you're missing a }, as you did here.
And 3.14 isn't an integer.
Are you joking? You're missing basic knowledges of Java:
1) Method yea doesn't have a return type.
2) There's a code directly inside the class Rectangle, not in method.
3) There's a code directly inside the class Square, not in method.
4) You're using very strange and weird code-style and formatting.
Update: Formatting has been fixed.
2nd Update:
1) Code has been changed and it's formatted wrong again.
2) There are three static methods without defined return type.
Here are some more informations related on the topic.
You need to change
int pi = 3.14;
to
double pi = 3.14;
Also, static method is in wrong place.

Pass an object of another class to a singleton class

I am using this singleton class in Java and in one method, I need an object of a class which gets instantiated in Main. I am not knowing how to pass that object to this method because this code is written in the constructor of the singleton class as I need it to be executed as soon as the program starts.
Should I take out the code from the constructor and make it a standalone method which I call from Main (though I wouldn't prefer this) or is there another way?
Any ideas?
Code:
Main:
public static void main(String[] args) {
X x; // This is the object I need to pass to the singleton class
}
Singleton class:
public SomeSingletonClass {
private Queue<Y> someQueue; // Y is another class I have in my project
private SomeSingletonClass(){
someQueue.add(new Y(<some data>, <some data>, <here I need an object of X as the constructor needs it>);
}
}
I haven't added the entire code. Just a fragment where I am stuck.
You have two main options.
The first will produce howls of derision - and rightly so because it is a dark tunnel of hell.
public class X {
}
public class Y {
public Y(String s, X x) {
}
}
public class Main {
public static X x = new X();
}
public class SomeSingletonClass {
private Queue<Y> someQueue = new LinkedList<>();;
private SomeSingletonClass() {
someQueue.add(new Y("Hello", Main.x));
}
}
Here we make the X created by Main a public static so it is now, essentially, global state in parallel with your singleton.
Most readers will understand how nasty this is but it is the simplest solution and therefore often the one taken.
The second option is lazy construction.
public class BetterSingletonClass {
private BetterSingletonClass me = null;
private Queue<Y> someQueue = new LinkedList<>();
private BetterSingletonClass(X x) {
someQueue.add(new Y("Hello", x));
}
public BetterSingletonClass getInstance (X x) {
if ( me == null ) {
me = new BetterSingletonClass(x);
}
return me;
}
}
Note that I have made no effort to make this a real singleton, n'or is this thread-safe. You can search for thread safe singleton elsewhere for plenty of examples.

Edit an object's methods after they've been created in Java

In JavaScript one can create and edit an object's functions on the fly. Is this possible with a Java object's methods? I am essentially wanting something like this:
public class MyObject{
private int x;
public MyObject(){x = 0;}
public myMethod(){}
}
MyObject foo = new MyObject();
and later call something along the lines of:
foo.myMethod = new method({x = 42;});
It's not directly possible, but you could try something like this:
public class MyObject {
private int x;
interface MyMethod {
void call();
}
public MyObject() {
x = 0;
}
public MyMethod myMethod = new MyMethod() {
#Override
public void call() {
x = 42;
}
};
}
You can't edit it in the way that you are trying to demonstrate above, the closest thing you could do to emulate it would be to intercept the method. The only way I could think of at the current moment is to use a MethodInterceptor found within the cglib library to intercept the method.
In Java you cannot do this like you would do it in Javascript.
But in Java you can achieve such an behavior using the Strategy pattern.
For example,
public interface Strategy {
void doSomething(MyObject obj);
}
public class BasicStrategy implements Strategy {
public void doSomething(MyObject obj) {
//do something
}
}
public class AnotherStrategy implements Strategy {
public void doSomething(MyObject obj) {
obj.setX(42);
}
}
public class MyObject {
private Strategy actualStrategy = new BasicStrategy();
private int x = 0;
public void executeStrategy() {
actualStrategy.doSomething(this);
}
public void setStrategy(Strategy newStrategy) {
actualStrategy = newStrategy;
}
public void setX(int x) {
this.x = x;
}
}
You can alter the behavior of the method at runtime using the following code.
MyObject obj = new MyObject();
obj.setStrategy(new AnotherStrategy());
obj.executeStrategy();
Yes, it's theoretically possible, but you don't want to do it. This sort of thing is black magic, and if you need to ask the question, you're several years from being ready to work with it.
That said, what you're trying to accomplish may be workable with the Strategy design pattern. The idea here is that you define an interface that has the method(s) you need to swap out (say, calculate()), and the class whose behavior you want to change has a field of that interface. You can then modify the contents of that field.
public interface Calculator {
double calculate(double x, double y);
}
public class MathStuff {
private Calculator calc;
...
public void doStuff() {
...
result = calc.calculate(x, y);
...
}
}
public class Add implements Calculator {
public double calculate(double x, double y) {
return x + y;
}
}
You cannot do this. In java new method is made to return the instance of class Object, not methods. And one thing is to understand is Javascript is an functional programming language and Java is a object oriented language. You cannot treat a method as object in java, also it breaks the security of java encapsulation.

Categories

Resources