how we can access class without it's object in Java or any object oriented programming language ?
how we can access the class without not using object ?
class test{
//elements of class
}
CodePudding user response:
It depends on what do you want to do.
If you want to a call method of the class, then according to OOP the simple answer is "you cannot". One must create an object to invoke methods.
Java has a special methods type - static methods. This sort of methods can be invoked using the class name instead of the object name:
public class Test {
public void someMethod() {
// do something
}
public static void someStaticMethod() {
// do something
}
}
Like this:
// calling non-static method
Test instanceOfTest = new Test();
instanceOfTest.someMethod();
// calling static method
Test.someStaticMethod();
Static methods are not covered by the classical OOP theory. It is a workaround provided by Java to support elements of functional programming.
CodePudding user response:
You can access class even without making any object
.
We normally make instances to use the methods
and the attributes
of the class.
However you can define some methods
and attributes
which are called static
s, these methods or attributes are for the class and not for the objects, so you can access those, just with the class:
Assume this example:
class Test{
public static void testStaticMethod(){
System.out.println("This method is static");
}
}
You can access the testStaticMethod
just by the class and without instantiating
any objects
:
class TestTester{
public static void main(String[] args){
Test.testStaticMethod()
}
}
Output:
This method is static
CodePudding user response:
class Test
{
public static String name = "Hello World";
public static String printValue(String name)
{
return "name is: " name;
}
}
public class MyClass {
public static void main(String args[]) {
System.out.println(Test.name);
System.out.println(Test.printValue("Hello"));
}
}