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?

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



Java OOPs Concepts With Examples

Java OOPs Concepts With Examples

In this post, we will understand the below core concepts of Object oriented Programming in the following sequence: Inheritance, Encapsulation, Abstraction, Polymorphism

Originally published by Aayushi Johari at https://www.edureka.co

Object Oriented programming is a programming style which is associated with the concepts like class, object, Inheritance, Encapsulation, Abstraction, Polymorphism. Most popular programming languages like Java, C++, C#, Ruby, etc. follow an object-oriented programming paradigm. As Java being the most sought-after skill, we will talk about object-oriented programming concepts in Java. An object-based application in Java is based on declaring classes, creating objects from them and interacting between these objects.

In this post, we will understand the below core concepts of Object oriented Programming in the following sequence:

  1. Inheritance
  2. Encapsulation
  3. Abstraction
  4. Polymorphism

Let’s get started with the first Object Oriented Programming concept i.e. Inheritance.

Object Oriented Programming : Inheritance

In OOP, computer programs are designed in such a way where everything is an object that interact with one another. Inheritance is one such concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes.

 As we can see in the image, a child inherits the properties from his father. Similarly, in Java, there are two classes:

1. Parent class ( Super or Base class)

2. Child class (Subclass or Derived class )

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.  

Inheritance is further classified into 4 types:

 

So let’s begin with the first type of inheritance i.e. Single Inheritance:

1 - Single Inheritance:

In single inheritance, one class inherits the properties of another. It enables a derived class to inherit the properties and behavior from a single parent class. This will in turn enable code reusability as well as add new features to the existing code.

Here, Class A is your parent class and Class B is your child class which inherits the properties and behavior of the parent class.

 Let’s see the syntax for single inheritance:

Class A
{
}
Class B extends A { }

2 - Multilevel Inheritance:

When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.

If we talk about the flowchart, class B inherits the properties and behavior of class A and class C inherits the properties of class B. Here A is the parent class for B and class B is the parent class for C. So in this case class C implicitly inherits the properties and methods of class A along with Class B. That’s what is multilevel inheritance.

Let’s see the syntax for multilevel inheritance in Java:

Class A{
}
Class B extends A{ }
Class C extends B{ }

3 - Hierarchical Inheritance:

When a class has more than one child classes (sub classes) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.

If we talk about the flowchart, Class B and C are the child classes which are inheriting from the parent class i.e Class A.

Let’s see the syntax for hierarchical inheritance in Java:

Class A{
}
Class B extends A{ }
Class C extends A{

}

4 - Hybrid Inheritance:

Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance. Since multiple inheritance is not supported in Java as it leads to ambiguity, so this type of inheritance can only be achieved through the use of the interfaces. 

If we talk about the flowchart, class A is a parent class for class B and C, whereas Class B and C are the parent class of D which is the only child class of B and C.

Now we have learned about inheritance and their different types. Let’s switch to another object oriented programming concept i.e Encapsulation.

Object Oriented Programming : Encapsulation

Encapsulation is a mechanism where you bind your data and code together as a single unit. It also means to hide your data in order to make it safe from any modification. What does this mean? The best way to understand encapsulation is to look at the example of a medical capsule, where the drug is always safe inside the capsule. Similarly, through encapsulation the methods and variables of a class are well hidden and safe.

We can achieve encapsulation in Java by:

  • Declaring the variables of a class as private.
  • Providing public setter and getter methods to modify and view the variables values.

Let us look at the code below to get a better understanding of encapsulation:

public class Employee {
 private String name;
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public static void main(String[] args) {
 }
}

Let us try to understand the above code. I have created a class Employee which has a private variable name. We have then created a getter and setter methods through which we can get and set the name of an employee. Through these methods, any class which wishes to access the name variable has to do it using these getter and setter methods.

Let’s move forward to our third Object-oriented programming concept i.e. Abstraction.

Object Oriented Programming : Abstraction

Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with hiding the details and showing the essential things to the user. If you look at the image here, whenever we get a call, we get an option to either pick it up or just reject it. But in reality, there is a lot of code that runs in the background. So you don’t know the internal processing of how a call is generated, that’s the beauty of abstraction. Therefore, abstraction helps to reduce complexity. You can achieve abstraction in two ways:

a) Abstract Class

b) Interface

Let’s understand these concepts in more detail.

Abstract class: Abstract class in Java contains the ‘abstract’ keyword. Now what does the abstract keyword mean? If a class is declared abstract, it cannot be instantiated, which means you cannot create an object of an abstract class. Also, an abstract class can contain abstract as well as concrete methods.

Note: You can achieve 0-100% abstraction using abstract class.

To use an abstract class, you have to inherit it from another class where you have to provide implementations for the abstract methods there itself, else it will also become an abstract class.

Let’s look at the syntax of an abstract class:

Abstract class Mobile {   // abstract class mobile
Abstract void run();      // abstract method

Interface: Interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Along with abstraction, interface also helps to achieve multiple inheritance in Java.

Note: You can achieve 100% abstraction using interfaces.

So an interface basically is a group of related methods with empty bodies. Let us understand interfaces better by taking an example of a ‘ParentCar’ interface with its related methods.

public interface ParentCar {
public void changeGear( int newValue);
public void speedUp(int increment);
public void applyBrakes(int decrement);
}

These methods need be present for every car, right? But their working is going to be different.

Let’s say you are working with manual car, there you have to increment the gear one by one, but if you are working with an automatic car, that time your system decides how to change gear with respect to speed. Therefore, not all my subclasses have the same logic written for change gear. The same case is for speedup, now let’s say when you press an accelerator, it speeds up at the rate of 10kms or 15kms. But suppose, someone else is driving a super car, where it increment by 30kms or 50kms. Again the logic varies. Similarly for applybrakes, where one person may have powerful brakes, other may not.

Since all the functionalities are common with all my subclasses, I have created an interface ‘ParentCar’ where all the functions are present. After that, I will create a child class which implements this interface, where the definition to all these method varies.

Next, let’s look into the functionality as to how you can implement this interface.

So to implement this interface, the name of your class would change to any particular brand of a Car, let’s say I’ll take an “Audi”. To implement the class interface, I will use the ‘implement’ keyword as seen below:

public class Audi implements ParentCar {
int speed=0;
int gear=1;
public void changeGear( int value){
gear=value;
}
public void speedUp( int increment)
{
speed=speed+increment;
}
public void applyBrakes(int decrement)
{
speed=speed-decrement;
}
void printStates(){
System.out.println("speed:"+speed+"gear:"+gear);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Audi A6= new Audi();
A6.speedUp(50);
A6.printStates();
A6.changeGear(4);
A6.SpeedUp(100);
A6.printStates();
}
}

Here as you can see, I have provided functionalities to the different methods I have declared in my interface class. Implementing an interface allows a class to become more formal about the behavior it promises to provide. You can create another class as well, say for example BMW class which can inherit the same interface ‘car’ with different functionalities.

So I hope you guys are clear with the interface and how you can achieve abstraction using it.

Finally, the last Object oriented programming concept is Polymorphism.

Object Oriented Programming : Polymorphism

Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. It is the ability of a variable, function or object to take on multiple forms. In other words, polymorphism allows you define one interface or method and have multiple implementations.

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

Let’s consider this real world scenario in cricket, we know that there are different types of bowlers i.e. Fast bowlers, Medium pace bowlers and spinners. As you can see in the above figure, there is a parent class- BowlerClass and it has three child classes: FastPacer, MediumPacer and Spinner. Bowler class has bowlingMethod() where all the child classes are inheriting this method. As we all know that a fast bowler will going to bowl differently as compared to medium pacer and spinner in terms of bowling speed, long run up and way of bowling, etc. Similarly a medium pacer’s implementation of bowlingMethod() is also going to be different as compared to other bowlers. And same happens with spinner class.

The point of above discussion is simply that a same name tends to multiple forms. All the three classes above inherited the bowlingMethod() but their implementation is totally different from one another.

Polymorphism in Java is of two types: 

  1. Run time polymorphism
  2. Compile time polymorphism

Run time polymorphism: In Java, runtime polymorphism refers to a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this, a reference variable is used to call an overridden method of a superclass at run time. Method overriding is an example of run time polymorphism. Let us look the following code to understand how the method overriding works:

public Class BowlerClass{
void bowlingMethod()
{
System.out.println(" bowler ");
}
public Class FastPacer{
void bowlingMethod()
{
System.out.println(" fast bowler ");
}
Public static void main(String[] args)
{
FastPacer obj= new FastPacer();
obj.bowlingMethod();
}
}

Compile time polymorphism: In Java, compile time polymorphism refers to a process in which a call to an overloaded method is resolved at compile time rather than at run time. Method overloading is an example of compile time polymorphism. Method Overloading is a feature that allows a class to have two or more methods having the same name but the arguments passed to the methods are different. Unlike method overriding, arguments can differ in:

  1. Number of parameters passed to a method
  2. Datatype of parameters
  3. Sequence of datatypes when passed to a method.

Let us look at the following code to understand how the method overloading works:

class Adder {
Static int add(int a, int b)
{
return a+b;
}
static double add( double a, double b)
{
return a+b;
}
 
public static void main(String args[])
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

I hope you guys are clear with all the object oriented programming concepts that we have discussed above i.e inheritance, encapsulation, abstraction and polymorphism. Now you can make your Java application more secure, simple and re-usable using Java OOPs concepts.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

100+ Java Interview Questions and Answers In 2019

Python vs Java: Understand Object Oriented Programming

Angular 7 + Spring Boot CRUD Example

Build a Simple CRUD App with Spring Boot and Vue.js

Securing RESTful API with Spring Boot, Security, and Data MongoDB