Java how to call method in another class - java

Sorry for the basic question but I'm learning, new to programming. I am trying to call a method that is in another class but I'm unable to without passing in the required values for the constructor of Cypher class. Do i really need a new instance of Cypher class each time i use a method in the Menu class and want to call a method of the Cypher class or how do I rewrite to avoid below.
public class Runner {
private static Cypher c;
public static void main(String[] args) {
Menu m = new Menu();
m.displayMenu();
//c=new Cypher(3,2);// wont work unless i add this line
c.displayCypher("text");
}
}
public class Cypher {
private int keyTotalRows;
private int keyStartRow;
public Cypher(int key, int offset) throws Exception {
}
public void displayCypher(String text) {
System.out.println("Plain text:" + text);
System.out.println("Key: Number of Rows:" + keyTotalRows + "\n" + "Key Start Row: " + keyStartRow);
}
}
public class Menu {
private Scanner s;
private void enterKey() {
s = new Scanner(System.in);
System.out.println("Enter key >");
int key = Integer.parseInt(s.next());
System.out.println("Enter offset >");
int offset = Integer.parseInt(s.next());
System.out.println(" Key:" + key + "\n" + " Offset:" + offset);
}
public static void displayMenu() {
System.out.println("Menu");
}

Few things:. Your methods are private which means you cannot call them outside the class.
change that and you will be able to create your object and call them.
Menu menu=new Menu() ;
menu.otherMethod();
However as the method calls c which is null you will get a null exception.
You should test for it and then call object c inner methods
If (this.c! =null)
{c.displayOtherCypherType("" ) ;}
else
{//do something here}
In order to be able to send Cypher from outside the class use a constructor that receives a Cypher object and assigns it to c or have a public set method that receives it and assigns it
public setCypher(Cypher cypher)
{
(this.c=cypher) ;
}
Now If you want to call Cypher methods without instantiating it you can create a static method inside it and call Tha method.
note that it to should be public or you won't be able to call it

You declare a Cypher type static variable c here. so you can't access the Cypher class method using c variable without object declaration. But you can call the c variable from any class because it's a static variable. But your Cypher class don't have any static Method so you can't call these methods without object initialization.
So you must declare a static method or need to create an object for the access method from Cypher class.
But if you declare Cypher type static variable with initialization. then you can call c from any class and also called Chyper class method using the c variable reference. like:
// Declare this on Runner class
public static Cypher c = new Cypher();
// And then call from any class like
Runner.c.yourMethod();
Happy Coding.

If you don't want to create an instance, you can make the method static.
Something like this:
public static void displayCypher(String text) {
System.out.println("Plain text:" + text);
System.out.println("Key: Number of Rows:" + keyTotalRows + "\n" + "Key Start Row: " + keyStartRow);
}
Then you can call this function in another class like
Cypher.displayCypher()

Related

Can a Java object factory be used as a constructor?

I'm pretty new to Java so hopefully this question isn't too stupid.
According to the Java documentation: "An object factory is a producer of objects. It accepts some information about how to create an object, such as a reference, and then returns an instance of that object."
How can that instance be the result of a constructor?
Here is some (totally pointless) example code that illustrates the class hierarchy I'm trying to construct (invoking it with simple integer arguments like "1 2 3" will get the point across):
package number;
public class Factory {
public static void main(String[] args) {
for (String arg : args) {
// This is how I want to instantiate and use the Outer class:
Outer outer = new Outer(arg);
// But I don't know how to create Outer from the factory, and the results are wrong:
System.out.println("yields: " + outer.value + ", class: " + outer.Class());
// This is a workaround (that I can't use) that gives the correct results:
Number number = outer.Workaround(arg);
System.out.println("yields: " + number.value + ", class " + number.Class());
}
}
}
class Outer extends Inner {
Outer(String arg) {
super(arg);
}
}
class Inner extends Number {
Inner(String arg) {
// I don't want to do this:
super(arg);
// I want some way of doing this:
// return NumberFactory.getNumber(arg);
}
// Workaround method that I can't really use:
Number Workaround(String arg) {
return NumberFactory.getNumber(arg);
}
}
class NumberFactory {
static Number getNumber(String selection) {
switch (selection) {
case "1": return new First(selection);
case "2": return new Second(selection);
default: return new Other(selection);
}
}
}
class First extends Number {
First(String arg) { super(arg); value = "first"; }
String Class() { return "First"; }
}
class Second extends Number {
Second(String arg) { super(arg); value = "second"; }
String Class() { return "Second"; }
}
class Other extends Number {
Other(String arg) { super(arg); value = "other"; }
String Class() { return "Other"; }
}
class Number {
String arg;
String value = "default";
Number(String arg) {
this.arg = arg;
System.out.print("Number(" + arg + "), ");
}
String Class() { return "Number"; }
}
please explain what you are trying to do.
but here's my attempt to answer your question.
Constructor is used when ever a new Java Object is created. When you use new SomeObject() compiler uses the constructor
SomeObject(){
// some logic here
}
to create an object using the SomeObject.class. How the object is created and maintained through its life-cycle is up to the JVM. you can find more info here. https://en.wikibooks.org/wiki/Java_Programming/Object_Lifecycle
Also object factories are used to create objects, but in turn they use object constructors to instantiate the object inside them (as you have already done so).
Object factories are used to delegate the logic of object creation to a central location, so that the code is not repeated and well organized.
Read more about object factories here https://github.com/iluwatar/java-design-patterns/tree/master/abstract-factory
another thing you dont have to implement String Class() method inside every class you implement. SomeObject.class.toString() will do it for you.
I couldn't understand your main question because java object factory is java's business and I don't think we can do anything with it, although I can try to answer your question regarding instances and constructor.....
Constructors in java are the way you talk to a class, even when you don't define a constructor of a class, a default constructor with default values(i.e., false for boolean etc.) is created for your class by the compiler.....So, I guess when you want specific way of creating a connection with your class then you make specific constructors otherwise a default is always made available by the compiler.
Maybe you want to ask why do we have to use super() before anything in a subclass constructor and the reason for that is again same i.e., The parent class' constructor needs to be called before the subclass' constructor. This will ensure that if you call any methods on the parent class in your constructor, the parent class has already been set up correctly.

what is the name of such invocation "variable.methodName(data);" ? [duplicate]

See the code snippets below:
Code 1
public class A {
static int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
short s = 9;
System.out.println(add(s, 6));
}
}
Code 2
public class A {
int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
A a = new A();
short s = 9;
System.out.println(a.add(s, 6));
}
}
What is the difference between these code snippets? Both output 15 as an answer.
A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();
Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:
MyClass.myMethod();
this.myMethod();
myMethod();
Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:
MyClass boston = new MyClassConstructor();
boston.myMethod("bostonURL");
MyClass miami = new MyClassConstructor();
miami.myMethod("miamiURL");
MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");
In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.
If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.
Generally
static: no need to create object we can directly call using
ClassName.methodname()
Non Static: we need to create a object like
ClassName obj=new ClassName()
obj.methodname();
A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
Reference:Static Vs Non-Static methods
Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.
A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.
In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.
Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -
A static method belongs to the class and a non-static method belongs to an object of a class.
I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
Now output will be:::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:
If your method is related to the object's characteristics, you should define it as non-static method. Otherwise, you can define your method as static, and you can use it independently from object.
Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();
Basic difference is non static members are declared with out using the keyword 'static'
All the static members (both variables and methods) are referred with the help of class name.
Hence the static members of class are also called as class reference members or class members..
In order to access the non static members of a class we should create reference variable .
reference variable store an object..
Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.
Another scenario for Static method.
Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.
Here, we have private constructor and using static method we are creating a object.
Ex::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
Demo obj1 = Demo.createObj();
Here, Only 1 instance will be alive at a time.
- First we must know that the diff bet static and non static methods
is differ from static and non static variables :
- this code explain static method - non static method and what is the diff
public class MyClass {
static {
System.out.println("this is static routine ... ");
}
public static void foo(){
System.out.println("this is static method ");
}
public void blabla(){
System.out.println("this is non static method ");
}
public static void main(String[] args) {
/* ***************************************************************************
* 1- in static method you can implement the method inside its class like : *
* you don't have to make an object of this class to implement this method *
* MyClass.foo(); // this is correct *
* MyClass.blabla(); // this is not correct because any non static *
* method you must make an object from the class to access it like this : *
* MyClass m = new MyClass(); *
* m.blabla(); *
* ***************************************************************************/
// access static method without make an object
MyClass.foo();
MyClass m = new MyClass();
// access non static method via make object
m.blabla();
/*
access static method make a warning but the code run ok
because you don't have to make an object from MyClass
you can easily call it MyClass.foo();
*/
m.foo();
}
}
/* output of the code */
/*
this is static routine ...
this is static method
this is non static method
this is static method
*/
- this code explain static method - non static Variables and what is the diff
public class Myclass2 {
// you can declare static variable here :
// or you can write int callCount = 0;
// make the same thing
//static int callCount = 0; = int callCount = 0;
static int callCount = 0;
public void method() {
/*********************************************************************
Can i declare a static variable inside static member function in Java?
- no you can't
static int callCount = 0; // error
***********************************************************************/
/* static variable */
callCount++;
System.out.println("Calls in method (1) : " + callCount);
}
public void method2() {
int callCount2 = 0 ;
/* non static variable */
callCount2++;
System.out.println("Calls in method (2) : " + callCount2);
}
public static void main(String[] args) {
Myclass2 m = new Myclass2();
/* method (1) calls */
m.method();
m.method();
m.method();
/* method (2) calls */
m.method2();
m.method2();
m.method2();
}
}
// output
// Calls in method (1) : 1
// Calls in method (1) : 2
// Calls in method (1) : 3
// Calls in method (2) : 1
// Calls in method (2) : 1
// Calls in method (2) : 1
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances

Understanding execution flow of this Java programme [duplicate]

This question already has answers here:
Why doesn't the compiler complain when I try to override a static method?
(9 answers)
Closed 6 years ago.
I'm new at learning Java can anyone explain me the execution flow of the following code? I'm quite confused with the output.
This is the code:
public class MainClass {
public static void main(String[] args) {
car c = new car();
vehicle v = c;
/* I am unable to understand what's happening while printing the values using the objects of the different classes*/
System.out.println("|" + v.getModelName()
+ "|" + c.getModelName()
+ "|" + v.getRegNo() + "|" + c.getRegNo() + "|");
}
}
class vehicle {
public static String getModelName() {
return "Volvo";
}
public long getRegNo() {
return 12345;
}
}
class car extends vehicle {
public static String getModelName() {
return "Toyota";
}
#Override
public long getRegNo() {
return 54321;
}
}
Object creation
You are creating car instance ( new car())
Add new object pointer to variable c
Copy content of variable c to variable vehicle ( which point to car object)
Method call flow
When you are call static function on object it will not apply inheritance rules, so in call to v.getModelName() Java Virtual Machine call method in class vehicle.
But when you are call car() object with vehicle pointer (v variable) getRegNo method of class vehicle will call and also when you are using car pointer (c variable) getRegNo method of class vehicle will call.
edite suggestion form comment:
This ability called "Polymorphism": here you can find good tutorial. "Polymorphism" is definitely as important a concept as "inheritance" and "encapsulation'.

For what purpose one would want to create a class's instance inside the same class's main?

I came across this kind of example and had difficulty to understand it's actuall purpose:
class YieldDemo extends Thread
{
static boolean finished = false;
static int sum = 0;
public static void main (String [] args)
{
new YieldDemo ().start ();
for (int i = 1; i <= 50000; i++)
{
sum++;
if (args.length == 0)
Thread.yield ();
}
finished = true;
}
public void run ()
{
while (!finished)
System.out.println ("sum = " + sum);
}
}
I've never seen this kind of implementation - why initiating a the new class inside the same class object and not outside the class? is there any particular reason?
In fact you are outside of the class object itself. The main method is a static method, thus it has no dependency on any object instance.
You could also move the main method to any other java file. In general it will also work. However, you need to put static methods in some file. As every java file needs to be a class, you may put the method in the class it works for. For example, the class Math in java is a pure utility class, it has no non-static method.
However, if you create something like this:
public final class Value {
private final int mValue;
public Value(int value) {
mValue = value;
}
public int getValue() {
return mValue;
}
public Value increase() {
return new Value(mValue + 1);
}
}
It can actually make sense if you want Value to be immutable (not change its internal value). So, calling increase() does not increase the value itself but creates a new instance of this object, with an increased value.

Inner Class change external variable java

I use Vaadin for my project and I have a question: How change variable external class franchSize?
TextField franchSize = new TextField();
franchSize.setDebugId("franch_size");
hl1.addComponent(franchSize);
franchSize.setValue("0");
hl1.setComponentAlignment(franchSize,
Alignment.MIDDLE_CENTER);
franchSize.addListener(new Property.ValueChangeListener() {
private static final long defaultValue = 0;
public void valueChange(ValueChangeEvent event) {
String value = (String) event.getProperty().getValue();
if(Integer.valueOf(value)%1==0){
franchSize.setValue("0");
franchSize.getWindow().showNotification("","Bla-bla-bla",Notification.TYPE_HUMANIZED_MESSAGE);
}
}
});
Error: "Cannot refer to a non-final variable franchSize inside an inner class defined in a different method" in "franchSize.setValue("0");" and "franchSize.getWindow().showNotification("","Bla-bla-bla",Notification.TYPE_HUMANIZED_MESSAGE);"
Here is a simple implementation for communicating with outer class variable,
public class Google01 implements Outer{
// outer class variable, see no final here
int outer = 0;
public static void main(String[] args) {
Google01 inst = new Google01();
inst.testMe();
}
public void testMe(){
// Inner class
class temp{
Outer out;
public temp(Outer out) {
this.out = out;
}
public void printMe(String text){
// reading outer variable
System.out.println(out.getValue() + text);
// setting outer variable
out.setValue(out.getValue() + 1);
}
}
// Lets start our test
temp obj = new temp(this);
System.out.println("Value of outer before call = " + outer);
// this should increment outer value, see number before Yahoo in output
obj.printMe("Yahooo");
obj.printMe("Google");
obj.printMe("Bing");
// Lets print outer value directly.
System.out.println("Value of outer after call = " + outer);
}
#Override
public void setValue(int value) {
outer = value;
}
#Override
public int getValue() {
return outer;
}
}
// An interface that is use to communicate with outer class variable.
interface Outer{
void setValue(int value);
int getValue();
}
Output
Value of outer before call = 0
0Yahooo
1Google
2Bing
Value of outer after call = 3
Brief Explaination:
You need to make an interface in order to talk to outer class ( I like making interface for communication but it can be done using passing outer class instance also instead of making whole new interface), and you can use the utility method provided by interface in order to get or put the value in outer class.
You can refer this to know why your error occur.
Only thing that i have changed in the scenario is that i have made the variable as class level variable (member variable) from method variable.
The error is pretty clear here: you cannot access a external variable inside an inner class without making it final. So just add final in front of TextField franchSize = new TextField();
make franchSize final -- as stated in the error message -- or use (TextField)event.getSource() instead of referencing the outer variable.
for informations about the error search SO
Just create a (private) field 'TextField franchSize' in the outer class.
Best way to access it then, is to use a protected getter.

Categories