How to use methods defined in anonymous class outside of it? - java

May I know how can I use/call the age method? Here is the Student class.
class Student {
public static void address(){
System.out.println("streetB");
}
}
public class School {
public static void main(String[] args) {
Student gg = new Student() {
public void age() {
System.out.println("9");
}
};
//how to call age() method here?
}
}

You are probably looking for something different, as you just created new class here that extends Student class, but it is anonymous so you can just access that new method as it does not belong to Student class.
If you are using java 10 then you can use var
class Student {
public static void address(){
System.out.println("streetB");
}
}
public class School {
public static void main(String[] args) {
var gg = new Student() {
public void age() {
System.out.println("9");
}
};
gg.age();
}
}
But that would be probably pretty bad idea, as there is just no reason to do such weird thing.
(var works here because it can represent that anonymous class at compile time)
You should probably add age field and method to Student class

Since gg is declared as Student and there is no age() method in that class, compiler will not allow you to call gg.age() because it is not guaranteed that every Student instance will be able to support it.
Pre java 10 solutions (if you are using Java 10 or later read this answer)
What you can try is reflection mechanism through which you can
gg.getClass() to get class literal representing actual type of object held by gg variable,
then getDeclaredMethod("age") to get age method declared in that class,
then invoke(gg) to call that method on object held by gg.
In short
gg.getClass().getDeclaredMethod("age").invoke(gg);
Other way would be not assigning created instance of anonymous class to any reference which would limit its possibility and call method directly on created object like
new Student() {
public void age() {
System.out.println("9");
}
}.age();
but this way we can't reuse that object anywhere later (because we don't have reference to it).

Related

How can I make classes implement an interface and print their methods based on a given parameter in Java?

I think this might be a very basic Java question, and I apologize since I'm a beginner, but I want to understand what am I getting wrong here: I'm supposed to create a package, and inside it, I must create the following:
an interface with a method (the question says nothing besides it, so I created it empty)
2 classes, A and B, which must implement the method created in said interface and print their own names
A third class, C, which must override B's implementation
And an Execute method inside the main class. This method must receive a letter as a parameter, no matter if it's capital case or not, and execute the method of the corresponding class (i.e. if this method receives as a parameter the letter A, it must execute the method belonging to class A)
So far I came up this this, but the code receives the input, and doesn't do anything:
Interface
public interface Test {
public static void testInterface() {
}
}
Classes
public class Teste {
public static void main(String[] args) {
class A implements Test {
public void testInterface() {
System.out.println("A");
}
}
class B implements Test {
public void testInterface() {
System.out.println("B");
}
}
class C extends B {
public void testInterface() {
System.out.println("C");
}
}
Scanner inputLetter = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter a letter from A to C: ");
String resLetter = inputLetter.nextLine(); // Read user input
if (resLetter == "A") {
A a = new A();
a.testInterface();
}
if (resLetra == "B") {
B b = new B();
b.testInterface();
}
if (resLetra == "C") {
C c = new C();
c.testInterface();
}
}
}
To be quite honest, I may be messing up with the code's structure too, since I'm not too sure of how should I organize it - I didn't create the Execute method because I had a lot of trouble creating classes without the main method, and couldn't put a method inside another, and I want to make it as simple as possible to make it work before I can try bolder things, so any help will be of great value!
You're on a good way. I'll just post some information to get you over your current roadblock.
public interface MyTestInterface {
void testInterface();
}
Interfaces will just "announce" a method. This just tells you (and the compiler) that any Class that implements MyTestInterface has to supply a method called testInterface(). Don't make them static, as this would prevent any class implementing the interface from overriding the method.
Put your classes in their own .java file. While you can define a class within a class (so called Inner Class), it has some implications.
A.java
public class A implements MyTestInterface {
#Override
public void testInterface() {
// Objects of Class A do something here
}
}
MyMain.java
public class MyMain {
public static void main(String[] args) {
MyTestInterface implementedByA = new A();
implementedByA.testInterface();
}
}
Since it implements MyTestInterface, an Object of Class A is both an instance of A and an instance of MyTestInterface. This allows you, to declare a variable of type MyTestInterface and assign it an implementation of one implementing class.
And as #Amongalen mentioned: How do I compare strings in Java?

Java Class with constructor asking for user input [duplicate]

I wrote this simple class in java just for testing some of its features.
public class class1 {
public static Integer value=0;
public class1() {
da();
}
public int da() {
class1.value=class1.value+1;
return 5;
}
public static void main(String[] args) {
class1 h = new class1();
class1 h2 = new class1();
System.out.println(class1.value);
}
}
The output is:
2
But in this code:
public class class1 {
public static Integer value=0;
public void class1() {
da();
}
public int da() {
class1.value=class1.value+1;
return 5;
}
public static void main(String[] args) {
class1 h = new class1();
class1 h2 = new class1();
System.out.println(class1.value);
}
}
The output of this code is:
0
So why doesn't, when I use void in the constructor method declaration, the static field of the class doesn't change any more?
In Java, the constructor is not a method. It only has the name of the class and a specific visibility. If it declares that returns something, then it is not a constructor, not even if it declares that returns a void. Note the difference here:
public class SomeClass {
public SomeClass() {
//constructor
}
public void SomeClass() {
//a method, NOT a constructor
}
}
Also, if a class doesn't define a constructor, then the compiler will automatically add a default constructor for you.
public void class1() is not a constructor, it is a void method whose name happens to match the class name. It is never called. Instead java creates a default constructor (since you have not created one), which does nothing.
Using void in the constructor by definition leads it to not longer be the constructor.
The constructor specifically has no return type. While void doesn't return a value in the strictest sense of the word, it is still considered a return type.
In the second example (where you use the void), you would have to do h.class1() for the method to get called because it is no longer the constructor. Or you could just remove the void.
This is arguably a design flaw in Java.
class MyClass {
// this is a constructor
MyClass() {...}
// this is an instance method
void MyClass() {...}
}
Perfectly legal. Probably shouldn't be, but is.
In your example, class1() is never getting called, because it's not a constructor. Instead, the default constructor is getting called.
Suggestion: familiarize yourself with Java naming conventions. Class names should start with uppercase.
The reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the run time.
Here is an article explaining this in greater detail:
https://www.quora.com/Why-is-the-return-type-of-constructor-not-void-while-the-return-type-of-a-function-can-be-void

What is the equivalent of :: operator in java?

When accessing a function from another class in c++,
we can write: classA::fct();
Is there an equivalent operator in java?
If not, how can we access a function from another class in java?
Well the ::-operator (Scope Resolution Operator) in C++ allows you to resolve ambiguous calls/references to identifiers. However, in java there are no independent functions as all functions are actually methods (members) of a class. As such there are no need for this operator, have a look here for differences between Java and C++ classes.
I am guessing you are attempting to access a member (possibly static) of a class, in which case you'd use the .-operator as exemplified in Mwesigye's answer or as follows:
public class AB {
public static void main(String[] args) {
B myB = new B();
myB.printA();
}
}
public class A {
public static int getInt() {
return 4;
}
}
public class B {
public void printA() {
System.out.println(A.getInt()); // output: 4
}
}
Here the .-operator is used to access printA() from the instantiated object myB (instantiated from class B). It is also used to access the static method getInt() whose implementation is tied to class A rather than any object of A. More info can be found here.
Take an example of a Class Student with methods what you call functions in c++
eg.
class Student{
//a non static method
public void getFees(){
//your logic
}
public static void deleteSubject(){
// your logic
}
}
class Club{
//create a new instance of student class
Student student = new Student();
public void printData(){
//access a non static method
student.getFees();
//accessing a static method
new Student().deleteSubject();
}
}
Hope this will help.

Surprising access to fields with Java anonymous class

I'm trying to better understand the concept of anonymous classes in Java. From other answers on this website, I learned that an anonymous class can access non-final fields of the enclosing class using OuterClass.this.myField.
I made the following simple test case with an interface, AnonInt, and a class AnonTest with a method foo which returns an instance of an anonymous class implementing AnonInt. Dspite the fact that I'm using System.out.println(a) rather than System.out.println(AnonTest.this.a) the code works and prints the correct result. How can this be?
public interface AnonInt {
void print();
}
public class AnonTest {
private int a;
public AnonTest(int a) {
this.a = a;
}
public AnonInt foo() {
return new AnonInt() {
public void print() {
System.out.println(a);
}
};
}
public static void main(String[] args) {
AnonTest at = new AnonTest(37);
AnonInt ai = at.foo();
ai.print();
}
}
Despite the fact that I'm using System.out.println(a) rather than System.out.println(AnonTest.this.a) the code works and prints the correct result. How can this be?
Since the reference to a is unambiguous in your context, the two expressions reference the same field.
Generally, AnonTest.this is required in a very specific context - when your method needs to access AnonTest object itself, rather than accessing one of its members. In case of your program, this is unnecessary: the compiler resolves the expression a to the object AnonTest.this.a, and passes it to System.out.println.

How do you transfer a variable defined in the main method of one class to another?

I have seen this done in many programs but I cant seem to follow the programming logic.
Lets say you have a simple class, ClassB. And in ClassB's main method you define an integer variable:
public class B {
public static void main(String[] args) {
int stuff = 333;
}
}
How can you transfer the variable to a different class, say ClassA, to be used.
public class A {
public static void main(String[] args) {
System.out.println(stuff);
}
}
Can someone please explain this to me in simple terms. I've been trying to learn this for 2 hours and cant wrap my head around it.
public static void main(String[] args) is meant to be used as a starting point for a Java program. Probably it's better to rename one of your methods to something else.
The problem you are seeing, is that the scope of the variable int stuff is limited to the main() method of class B, because it is declared within the body of the main() method. In order to make it visible, you need to declare it as a public field (which can be static in your case).
I propose you change your program like follows:
public class A {
public static int stuff;
public static void initStaticMembers() {
stuff = 333;
}
}
public class B {
public static void main(String[] args) {
A.initStaticMembers();
System.out.println(A.stuff);
}
}
I renamed the main() method of A to initStaticMembers() and dropped the method parameters, since they are not needed in our case. In order to use the field A.stuff in B, the method A.initStaticMembers() needs to be called first.
Of course there are ways to improve this program, but I think you should learn Java one step at a time.
You shouldn't have 2 main methods. Only one class should (typically):
ClassA.java
public class A {
public static void main(String[] args) {
ClassB b = new ClassB();
System.out.println(b.stuff);
}
}
ClassB.java
public class B {
public int stuff = 333; // member variable
}
You instantiate the second class in the first one, then you're granted access to its public member variables.

Categories

Resources