What is the equivalent of :: operator in java? - 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.

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?

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

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).

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

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.

Class Methods Inheritance

I was told that static methods in java didn't have Inheritance but when I try the following test
package test1;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
TB.ttt();
TB.ttt2();
}
}
package test1;
public class TA {
static public Boolean ttt()
{
System.out.println("TestInheritenceA");
return true;
}
static public String test ="ClassA";
}
package test1;
public class TB extends TA{
static public void ttt2(){
System.out.println(test);
}
}
it printed :
TestInheritenceA
ClassA
so do java static methods (and fields) have inheritance (if you try to call a class method does it go along the inheritance chain looking for class methods). Was this ever not the case? And are there any inheritance OO languages that are messed up like that for class methods?
So apparently static methods are inherited but can't be overidden, so does c# share that problem? Do any other Languages?
In Java, fields and static methods are inherited, but cannot be overridden - I believe that is what whoever told you that "they are not inherited" meant.
Non-private, non-static methods are inherited and can be overridden.
This was always the case, but you cannot override class methods:
class A {
public static void a() { system.out.println("A"); }
}
class B {
public static void a() { system.out.println("B"); }
}
A a = new A();
a.a(); // "A"
B b = new B();
b.a() // "B"
a = b;
a.a(); // "A"
That's the meaning of static. It means per class. Static fields and methods are shared among instances. If you change a static value, it's reflected across instances.

Categories

Resources