How to call method from another class?

So I'm a rookie at OOP and I am currently having trouble using a function from another method. The class below is the main class for a card game. Here it creates a deck of cards by creating an object from the Game class. It then starts the game with the created deck and should print the size of the deck.

So I'm a rookie at OOP and I am currently having trouble using a function from another method. The class below is the main class for a card game. Here it creates a deck of cards by creating an object from the Game class. It then starts the game with the created deck and should print the size of the deck.

public class Run {

public static void main(String[] args) {

Game game;
System.out.println("Welcome!");
play = true;
while (play) {
    game = new Game(3); //Create deck of card based on number of ranks given
    game.play(); //Starts the game with deck of card
}

}

The class below is the Game class. When the game starts it should print the size of the deck created.

public class Game {
public Game(int ranks)
{
Deck Main = new Deck(ranks);
}
public static void play()
{
System.out.println(Main.size()); //Where the error occurs
}

The class below is the Deck class where it actually creates the deck and has a method that returns the size of that deck.

public class Deck {

private ArrayList<Card> cards;

public Deck(int range) {
cards = new ArrayList<Card>();
for (int i=1; i<=range; i++)
{
Card card = new Card(1, i);
Card card2 = new Card(2, i);
Card card3 = new Card(3, i);
Card card4 = new Card(4, i);
cards.add(card);
cards.add(card2);
cards.add(card3);
cards.add(card4);
}
}
public int size()
{
int num=cards.size();
return num;
}

The final class is the Card class.

public class Card {
private int rank;
private int suit;
public Card(int s, int r)
{
suit=s;
rank=r;
}
public int getSuit()
{
return suit;
}
public int getRank()
{
return rank;
}

It must be an obvious error due to my lack of understanding so can anyone show what to do to fix it?

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

Description
This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language. This is the first course where we will study the Fundamentals of Java, and we will take you step by step until you acquire the bases of the Java language and you can start to study more advanced Java topics.

The content is divided into perfectly structured levels, each level supported by the previous one, with the aim of adding Java knowledge incrementally and so you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

We will also offer support for any doubts about the didactic material included in this Java Fundamentals course.

We manage a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to be studied, complemented by eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since As we know we can not do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises that will allow you to accelerate your eLearning learning. No loss of time in videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the Java professional and working world.

The Java Fundamentals course includes the following topics for study:

Lesson 1 - Starting with Java Technology

The amazing world of Java programming

What is Java technology (from a practical approach)

Our first Java program from scratch

Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for

Types of Data in Java and how they are classified

Management and Classification of operators in Java

Lesson 3 - Control statements in Java

Using the if-else structure and where to use it

Handling the switch structure and when applying it

Lesson 4 - Handling Loops in Java

Use of the for loop and its use

Using the while loop and how to apply it

Use of the do-while loop and when to use it

Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)

Handling Classes in Java

Use of Objects in Java

Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java

Use and call of functions in Java

Lesson 7 - Data Management in Java

Using Arrays in Java

Management of Matrices in Java

Lesson 8 - Inheritance in Java

Inheritance Management in Java

Use of superclasses and subclasses in Java

Final Level Laboratory

Final Exercise where everything learned in this Level is integrated

At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you on the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn how to program in Java
Basic knowledge
Basic knowledge of PC use
Basic management of an operating system such as Windows, Mac or Linux
It is not necessary to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Manage the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn the Control Statements and Loops in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrays in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To know more:

Polymorphism In Java — How To Get Started With OOPs?

Polymorphism In Java — How To Get Started With OOPs?

<strong>This article on Polymorphism in Java talks about one of the key concepts of object oriented programming in depth.</strong>

This article on Polymorphism in Java talks about one of the key concepts of object oriented programming in depth.

In the real world, you might have seen a chameleon changing its color as per its requirement. If someone asks, “How it does that?”, you can simply say, “Because, it is polymorphic”. Similarly, in the programming world, Java objects possess the same functionality where each object can take multiple forms. This property is known as Polymorphism in Java, where Poly means many and morph means change (or ‘form’). In this article, let’s discuss this key concept of Object Oriented Programming i.e. Polymorphism in Java.

Below are the topics to be covered in this article:

  • What is Polymorphism?
  • Polymorphism in Java with Example
  • Types of Polymorphism in Java
  1. Static Polymorphism
  2. Dynamic Polymorphism
  • What is Polymorphism?
  • Polymorphism in Java with Example
  • Types of Polymorphism in Java

You can go through this OOPs concepts video lecture from where you can learn each & every nitty gritties of the technology.

What is Polymorphism?

Polymorphism is the ability of an entity to take several forms. In object-oriented programming, it refers to the ability of an object (or a reference to an object) to take different forms of objects. It allows a common data-gathering message to be sent to each class. Polymorphism encourages called as ‘extendibility’ which means an object or a class can have it’s uses extended.

In the above figure, you can see, Man is only one, but he takes multiple roles like — he is a dad to his child, he is an employee, a salesperson and many more. This is known as Polymorphism.

Now, let’s understand this by taking a real-life example and see how this concept fits into Object-oriented programming.

Polymorphism in Java with Example

Let’s understand this (the example) with the help of below problem statement.

Consider a cell phone where you save your Contacts. Suppose a person has two contact numbers. For the ease of accessibility, your cellphone provides you the functionality where you can save two numbers under the same name.
Similarly, in Java, an object is only one but it can take multiple forms depending on the context of the program. Suppose you want to write a function to save two contact numbers of the same person, you can create it like — void createContact(String name, int number1, int number2).

Now, it’s not necessary that everyone in your contact list will have two contact numbers. Few of them might be having only a single contact number. In such situations, instead of creating another method with a different name to save one number for a contact, what you can do is, create another method with the same name i.e. createContact(). But, instead of taking two contact numbers as parameters, take only one contact number as a parameter i.e. void createContact(String name, int number1).

As you can see in the above figure, createContact() method has two different definitions. Here, which definition is to be executed depends upon the number of parameters being passed. If one parameter is passed, then only a single contact number is saved under the contact. But, if two contact numbers are passed to this method at the same time, then both will be saved under the same contact. This is also known as Method Overloading*.*

Now let’s take another example and understand polymorphism in depth.

Consider a cell phone where you save your Contacts. Suppose a person has two contact numbers. For the ease of accessibility, your cellphone provides you the functionality where you can save two numbers under the same name.
Now relating this concept to an object-oriented language like Java, suppose you have a class named XJeans which includes a method named jeans(). Using this method, you can get an Allen Solly jeans. For the Jeans in the neighboring town, there is another class YJeans. Both the classes XJeans and YJeans extends the parent class ABCShoppingCenter. The YJeans class includes a method named jeans(), using which you can get both the jeans variants.

classABCShoppingCenter {
public void jeans() {
System.out.println("Default AllenSolly Jeans");
}
}
class XJeans extends ABCShoppingCenter {
public void jeans() {
System.out.println("Default AllenSolly Jeans");
}
}
class YJeans extends ABCShoppingCenter { 
// This is overridden method
public void jeans() {
System.out.println("New variant of AllenSolly");
} 
}

So, instead of creating different methods for every new variant, we can have a single method jeans**()**, which can be defined as per the different child classes. Thus, the method named jeans() has two definitions — one with only default jeans and other with both, the default jeans and the new variant. Now, which method gets invoked will depend on the type of object it belongs to. If you create ABCShoppingCenter class object, then there will be only one jeans available. But if you create YJeans class object, that extends ABCShoppingCenter class, then you can have both the variants. This is also known as Method Overriding*.* Thus, Polymorphism increases the simplicity and readability of the code by reducing the complexity. This makes Polymorphism in Java a very useful concept and it can be applied in real-world scenarios as well.

I hope you got an idea on the concept of Polymorphism. Now, let’s move further with this article and understand different types of Polymorphism in Java.

Types of Polymorphism in Java

Java supports two types of polymorphism and they are as follows:

  • What is Polymorphism?
  • Polymorphism in Java with Example
  • Types of Polymorphism in Java

Static Polymorphism

A polymorphism that is resolved during compile time is known as static polymorphism. Method overloading is an example of compile time polymorphism.

Example

Method Overloading is a feature that allows a class to have two or more method to have the same name, but with different parameter lists. In the below example, you have two definitions of the same method add(). So, which add() method would be called is determined by the parameter list at the compile time. That is the reason this is also known as compile time polymorphism.

class Calculator
{
int add(int x, int y)
{
return x+y;
}
int add(int x, int y, int z) 
{
return x+y+z;
}
}
public class Test
{
public static void main(String args[])
{
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
System.out.println(obj.add(100, 200, 300));
}
}

This is how Static Polymorphism works. Now, let’s understand what is Dynamic Polymorphism in Java.

Dynamic Polymorphism

Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime, that’s why it is called runtime polymorphism. Method Overriding is one of the ways to achieve Dynamic Polymorphism. In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.

Example

 In the below example, you have two classes MacBook and iPadMacBook is a parent class and iPad is a child class. The child class is overriding the method myMethod() of the parent class. Here, I have assigned child class object to the parent class reference to determine which method would be called at run-time. It is the type of object that determines which version of the method would be called (not the type of reference).

class MacBook{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class iPad extends MacBook{
public void myMethod(){
System.out.println("Overriding Method");
}
public static void main(String args[]){
MacBook obj = new iPad();
obj.myMethod();
}
}

Output:

Overriding Method

When you invoke the overriding method, then the object determines which method is to be executed. Thus, this decision is made at the run time.

I have listed down few more overriding examples.

MacBook obj = new MacBook();
obj.myMethod();
// This would call the myMethod() of parent class MacBook

iPad obj = new iPad();
obj.myMethod();
// This would call the myMethod() of child class iPad

MacBook obj = new iPad();
obj.myMethod();
// This would call the myMethod() of child class iPad

In the third example, the method of the child class is to be executed because the method that needs to be executed is determined by the type of object. Since the object belongs to the child class, the child class version of myMethod() is called.

Advantages of Dynamic Polymorphism

  1. Static Polymorphism
  2. Dynamic Polymorphism

This was all about different types. Now let’s see some important other characteristics of Polymorphism.

Other Characteristics of Polymorphism in Java

In addition to these two main types of polymorphism in Java, there are other characteristics in the Java programming language that exhibits polymorphism like:

  • What is Polymorphism?
  • Polymorphism in Java with Example
  • Types of Polymorphism in Java

Let’s discuss some of these characteristics.

Coercion

Polymorphic coercion deals with implicit type conversion done by the compiler to prevent type errors. A typical example is seen in an integer and string concatenation.

String str="string"=2;

Operator Overloading

An operator or method overloading refers to a polymorphic characteristic of same symbol or operator having different meanings (forms) depending on the context. For example, the plus symbol (+) is used for mathematical addition as well as String concatenation. In either case, only context (i.e. argument types) determines the interpretation of the symbol.

String str = "2" + 2;
int sum = 2 + 2;
System.out.println(" str = %s\n sum = %d\n", str, sum);

Output:

str = 22sum = 4

Polymorphic Parameters

Parametric polymorphism allows a name of a parameter or method in a class to be associated with different types. In the below example I have defined content as a String and later as an Integer:

public class TextFile extends GenericFile{
private String content;
public String setContentDelimiter(){
int content = 100;
this.content = this.content + content;
}
}

Note: Declaration of polymorphic parameters can lead to a problem known as variable hiding**.**

Here, the local declaration of a parameter always overrides the global declaration of another parameter with the same name. To solve this problem, it is often advisable to use global references such as this keyword to point to global variables within a local context.

With this, we come to an end on Polymorphism in Java article. Do look out for other articles and videos in the series which will help you understand various concepts of Java.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Object Oriented Programming (OOP) Java Tutorial for Beginners

Object Oriented Programming (OOP) Java Tutorial for Beginners

Learn/Brush up Object Oriented Programming(OOP) skills using Java Programming Language and apply them in real time

Learn/Brush up Object Oriented Programming(OOP) skills using Java Programming Language and apply them in real time

This video is absolutely apt for you if you are already familiar with programming foundations and looking to learn or brush up Object Oriented Programming features, The fundamental focus point of this course is to explain you, what the feature is, using a simple and easy to understand example and also help you understand how you can apply it in real world software development.

It is imperative that if you are looking to be a Java professional, you must possess good clarity in programming fundamentals, and applying the object oriented programming (OOP) features in your code. This can be achieved provided that you know answers to few questions such as what the feature is all about? when to apply? how to apply? as understanding these features are very critical for software development.

You’ll learn

Learn Object Oriented Programming features through Java Programming Language.

Gain the insights about how you can apply them in the real time in software development.


Learn More

How to do internationalization (i18n) in Java 11, Spring Boot, and JavaScript

Learn Java from Beginner to Advanced - Complete Java Course Part 1/3

Functional programming for Java developers

Java 12 and IntelliJ IDEA

Complete Java Masterclass

Java Web Service Complete Guide - SOAP + REST + Buide App

Selenium WebDriver with Java - Basics to Advanced& Interview