Use java class in another class

Use java class in another class

Объясните кто знает что за модификатора доступа (package private)? Чем он отличается от обычного private? Могу предположить что автор имел ввиду default access modifier, поправьте если не прав.

Продолжение про нестатические вложенные (анонимные) классы (2/3 часть): https://javarush.com/groups/posts/2193-anonimnihe-klassih Продолжение про статические вложенные классы (3/3 часть): https://javarush.com/groups/posts/2183-staticheskie-vlozhennihe-klassih

Зачем давать не актуальную информацию? Внутренний класс МОЖЕТ содержать статические переменные и методы но с JAVA 16.

В шестом пункте написано » Если у внутреннего класса нет модификатора доступа (package private), объекты внутреннего класса можно создавать внутри «внешнего» класса;» , а если есть, то нельзя?

Так же protected работает и для внутренних классов. Объекты protected внутреннего класса можно создавать: внутри «внешнего» класса; в его классах-наследниках; в тех классах, которые находятся в том же пакете. Может кто подсказать, что за хрень творится с этим модификатором доступа? Почему я не могу создать экземпляр внутреннего класса в классе-наследнике (наследование от внешнего класса, так как от внутреннего protected компилятор не дает наследоваться) в другом пэкадже? Хотя в статье говориться, что я могу это сделать.

Читайте также:  Телеграмм бот напоминания python

Вообще не понимаю что тут написано 🤷🏽‍♂️ «Объект внутреннего класса нельзя создать в статическом методе «внешнего» класса. Это объясняется особенностями устройства внутренних классов. У внутреннего класса могут быть конструкторы с параметрами или только конструктор по умолчанию. Но независимо от этого, когда мы создаем объект внутреннего класса, в него незаметно передается ссылка на объект «внешнего» класса. Ведь наличие такого объекта — обязательное условие. Иначе мы не сможем создавать объекты внутреннего класса. Но если метод внешнего класса статический, значит, объект внешнего класса может вообще не существовать! А значит, логика работы внутреннего класса будет нарушена. В такой ситуации компилятор выбросит ошибку:

 public static Seat createSeat() < //Bicycle.this cannot be referenced from a static context return new Seat(); >

Объект внутреннего класса нельзя создать в статическом методе «внешнего» класса. Может быть его нельзя создать не потому что есть или нет объекта внешнего класса, который можно создать по дефолту, а потому что в статических методах нельзя использовать нестатические переменные? public class Main < public static void main(String[] args) < Outer obj = new Outer(); Outer.Inner obj1 = obj.getObj(); System.out.println(obj1.a); >> class Outer < static class Inner < int a = 5; >static Inner getObj() < return new Inner(); >>

Источник

How to call a method from another Class Java

In Java, methods/functions are nothing but a set of instructions or a block of code that will come into action when someone calls it. A method can have different instructions that work combinedly to perform a specific task. The code specified within the method will get executed only when someone calls it. In Java, methods are of two types i.e. user-defined and predefined methods.

In Java, a method can be invoked within the same class as well as from some other java class. Any method regardless of its type i.e. predefined or user-defined will be invoked/called using the dot syntax.

This post will present an in-depth overview of how to invoke a java method from another class with the help of examples. So, let’s get started!

Invoking a Java method from another class

We have to create the object of a class(class to be invoked) to invoke a method of one class in some other java class.

Let’s consider an example to understand how to invoke a method from another Java class:

  • Let’s say we have two classes i.e. “FirstClass” and “SecondClass”.
  • We assume that the “FirstClass” has a method named “Hello()” and we have to invoke it in the “SecondClass”.
  • To do that, first, we need to create an object of “FirstClass” in the main method of the “SecondClass”.
  • Once an object of the “FirstClass” is created, then we can invoke any method or attribute of the “FirstClass” within the “SecondClass” using that object.

Calling a public method from another class

We all know that programming languages have some access modifiers that define the scope/accessibility of a method, constructor, or class. “public” is one of them that is accessible inside as well as outside of a class/package.

Example: invoke a public method from some other class
In this program, we will create two classes “FirstClass” and “SecondClass” as shown in the below-given code blocks:

class FirstClass {
public void printMessage ( ) {
System. out . println ( «Welcome to linuxhint.com» ) ;
}
}

In the “FirstClass”, we created a method named “printMessage()” which will show a message “welcome to linuxhint.com” whenever someone invokes it.

SecondClass

public class SecondClass {
public static void main ( String [ ] args ) {
FirstClass classObj = new FirstClass ( ) ;
classObj. printMessage ( ) ;
}
}

The “SecondClass” served the below-listed functionalities:

  • Created an object of the “FirstClass” using a new Keyword.
  • Invoked the “printMessage()” method using the object of the “FirstClass”.

The output proved that the “printMessage()” method of the “FirstClass” was successfully invoked from the “SecondClass”.

Calling a protected method from another Java class

In java, if a method of a class is declared with the “protected” keyword, then it can be accessed by any other class of the same package. A method declared with the protected keyword can’t be accessed out of the package directly. However, it can be accessed outside the package with the help of inheritance.

Example: how to invoke a protected method from some other class of the same package
In the following program, we will create two classes “FirstClass” and “SecondClass”:

class FirstClass {
protected void printDomainName ( ) {
System. out . println ( «Linuxhint.com» ) ;
}
}

Within FirstClass, we created a method named “printDomainName()” with the protected access modifier.

SecondClass:

Within the second class, firstly, we created an object of the “SecondClass”. Afterwards, we utilized that object to invoke the “printDomainName()” method of the FirstClass.

The above snippet verifies that we can call the protected method from some other class of the same package.

Calling a static method from another class

In Java, there is no need to create the object of a class while working with the static methods. A static method of one class can be invoked from some other class using the class name.

Example: How to invoke a static method from another class?

class FirstClass {
static void printDomain ( ) {
System. out . println ( «this is linuxhint.com» ) ;
}
}

public class SecondClass {
public static void main ( String [ ] args ) {
FirstClass. printDomain ( ) ;
}
}

In this example program, we created two classes “FirstClass” and “SecondClass”. We invoked the static method of the “FirstClass” from the main method of the “SecondClass”. Consequently, we will get the following output:

The output verified that the static method of one class can be accessed/invoked from another class directly with the class name.

Conclusion

In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance. A static method of one class can be invoked from some other class using the class name. This write-up considered multiple examples to explain how to call a method from another class in Java.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

How to call a method from another Class Java

In Java, methods/functions are nothing but a set of instructions or a block of code that will come into action when someone calls it. A method can have different instructions that work combinedly to perform a specific task. The code specified within the method will get executed only when someone calls it. In Java, methods are of two types i.e. user-defined and predefined methods.

In Java, a method can be invoked within the same class as well as from some other java class. Any method regardless of its type i.e. predefined or user-defined will be invoked/called using the dot syntax.

This post will present an in-depth overview of how to invoke a java method from another class with the help of examples. So, let’s get started!

Invoking a Java method from another class

We have to create the object of a class(class to be invoked) to invoke a method of one class in some other java class.

Let’s consider an example to understand how to invoke a method from another Java class:

  • Let’s say we have two classes i.e. “FirstClass” and “SecondClass”.
  • We assume that the “FirstClass” has a method named “Hello()” and we have to invoke it in the “SecondClass”.
  • To do that, first, we need to create an object of “FirstClass” in the main method of the “SecondClass”.
  • Once an object of the “FirstClass” is created, then we can invoke any method or attribute of the “FirstClass” within the “SecondClass” using that object.

Calling a public method from another class

We all know that programming languages have some access modifiers that define the scope/accessibility of a method, constructor, or class. “public” is one of them that is accessible inside as well as outside of a class/package.

Example: invoke a public method from some other class
In this program, we will create two classes “FirstClass” and “SecondClass” as shown in the below-given code blocks:

class FirstClass {
public void printMessage ( ) {
System. out . println ( «Welcome to linuxhint.com» ) ;
}
}

In the “FirstClass”, we created a method named “printMessage()” which will show a message “welcome to linuxhint.com” whenever someone invokes it.

SecondClass

public class SecondClass {
public static void main ( String [ ] args ) {
FirstClass classObj = new FirstClass ( ) ;
classObj. printMessage ( ) ;
}
}

The “SecondClass” served the below-listed functionalities:

  • Created an object of the “FirstClass” using a new Keyword.
  • Invoked the “printMessage()” method using the object of the “FirstClass”.

The output proved that the “printMessage()” method of the “FirstClass” was successfully invoked from the “SecondClass”.

Calling a protected method from another Java class

In java, if a method of a class is declared with the “protected” keyword, then it can be accessed by any other class of the same package. A method declared with the protected keyword can’t be accessed out of the package directly. However, it can be accessed outside the package with the help of inheritance.

Example: how to invoke a protected method from some other class of the same package
In the following program, we will create two classes “FirstClass” and “SecondClass”:

class FirstClass {
protected void printDomainName ( ) {
System. out . println ( «Linuxhint.com» ) ;
}
}

Within FirstClass, we created a method named “printDomainName()” with the protected access modifier.

SecondClass:

Within the second class, firstly, we created an object of the “SecondClass”. Afterwards, we utilized that object to invoke the “printDomainName()” method of the FirstClass.

The above snippet verifies that we can call the protected method from some other class of the same package.

Calling a static method from another class

In Java, there is no need to create the object of a class while working with the static methods. A static method of one class can be invoked from some other class using the class name.

Example: How to invoke a static method from another class?

class FirstClass {
static void printDomain ( ) {
System. out . println ( «this is linuxhint.com» ) ;
}
}

public class SecondClass {
public static void main ( String [ ] args ) {
FirstClass. printDomain ( ) ;
}
}

In this example program, we created two classes “FirstClass” and “SecondClass”. We invoked the static method of the “FirstClass” from the main method of the “SecondClass”. Consequently, we will get the following output:

The output verified that the static method of one class can be accessed/invoked from another class directly with the class name.

Conclusion

In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance. A static method of one class can be invoked from some other class using the class name. This write-up considered multiple examples to explain how to call a method from another class in Java.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

Оцените статью