Classes Overview: Reuse The Class Properties

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

Classes Overview

 Eclipse: Oxygen
 Java: 1.8

Classes and Objects are the basic building block of Object Oriented Programming language. The
class can be created by using “class” keyword followed by a reference name.

Syntax:

class Car {
//class body
}
Classes are the blueprint of object creation. Classes are the user-defined implementation of real-life
scenarios. A class defines the state and behaviour of an object.

State – It is the property or variables declared inside a class.


Behaviour – It is the functions or methods created inside a class.
In the following example of a Car class, variables declared inside the class are the properties, and
methods which define the start and acceleration of the class Car are the behaviour.

public class Car {


 
private String doors;
private String engine;
private String drivers;
public int speed;

}
Reuse the Class Properties
Class properties are used to create a new class as a type of an existing class which includes some
common properties. And these common properties can be driven to the new class from the existing
class.

In the following example, the class Car has some properties like doors, engine, speed, and driver.
We will reuse the Car class properties in another “Hello” class.

To access the object of the “Car” class we have to create the object of the “Car” class in “Hello”
class.

new Car(); is the object of Car class which is referenced by obj variable.
public class Car {
private String doors;
private String engine;
private String drivers;
public int speed;
 
}
public class Hello {
public static void main(String[] args) {
Car obj = new Car();
obj.speed=1;
System.out.println(obj.speed);

}
 
}
Output:

Classes-Getters and Setters:


In Java, Getter and setter methods are used to retrieve and update the private variables. When you
hide the implementation of the object of the class from the outer world, you declare them as private.
As private members of the class are not accessible from outside the class, so we use the getter and
setter method to retrieve and update the values of private members.

In the following example, we have declared some private variables inside the class. We will write
getter and setter methods for the variables.

We can manually write the getter and setter method for variable “speed”. The setter method is a
parameterized method with return type as void, which is used to update the value. Getter method
has a return type which will be the same as the data type of private variable.
public class Car {
private String doors;
private String engine;
private String drivers;
private int speed;

public void setspeed(int speed) {


this.speed=speed;
}

public int getspeed() {


return speed;
}
 
}
To access the properties (variable) and functionalities (methods) of “car” in another class, we have
to create the object of car class.
public class Hello{
public static void main(String[] args) {
Car car = new Car ();
car.setspeed (10);
System.out.println (car.getspeed());
}
}
Output
10

You can generate the getter and setter method for all remaining variable in the class, from the
source menu in eclipse.

Source >> Generate Getter and Setter


After generating the getter and setter method you can easily set the values.

public class Car {


private String doors;
private String engine;
private String drivers;
private int speed;
 
public int getspeed() {
return speed;
}
 
public void setspeed(int speed) {
this.speed = speed;
}
 
public String getDoors() {
return doors;
}
 
public void setDoors(String doors) {
this.doors = doors;
}
 
public String getEngine() {
return engine;
}
 
public void setEngine(String engine) {
this.engine = engine;
}
 
public String getDrivers() {
return drivers;
}
 
public void setDrivers(String drivers) {
this.drivers = drivers;
}
 
}

Adding functions to a class


Likewise, the class has properties, it also has functions or methods. In the following example, we will
create a function in the class.

In this code we are validating the car’s behavior on multiple conditions. “run” function will return the
behavior according to the applied conditions. Properties of the car are set in different class.

public class Car {


private String doors;
private String engine;
private String driver;
private int speed;
public String run() {
if(doors.equals("closed") && engine.equals("on")&& driver.equals("seated")
&& speed >0) {
return "car is running";
}else {
return "car is not running";
}
}
Again, we call the properties and function of Car class by using the object of Car class.
public static void main(String[] args) {
Car car = new Car ();
car.setspeed (10);
car.setDoors ("closed");
car.setEngine ("on");
car.setDrivers ("seated");
//calling the function
System.out.println (car.run ());

}
Output
car is running

Constructor Overview
 Eclipse: Oxygen
 Java: 1.8

Constructor Introduction:
In Java, Constructor is a special method, which is invoked when an object of the class is created. It
is used to initializing the class variables.

There are some rules for construction creation:

 A constructor always has the same name as the class name.


 A constructor is a special method which does not has any return type

public class Car {

public Car() {

//code block
}

}
The constructor is of two types
 Default constructor
 Parameterized constructor
Default Constructor – If you do not have any constructor in your class, Java compiler adds a default
constructor to the class during compilation.
In the following example, we did not use the object of the class to initialize the variable, rather all the
variables have been initialized using a constructor.

public class Car {

private String doors;


private String engine;
private String driver;
private int speed;

public Car() {
doors = "closed";
engine = "on";
driver= "seated";
speed = 10;

}
 
public String run() {
if(doors.equals("closed") && engine.equals("on")&& driver.equals("seated")
&& speed >0) {
return "car is running";
}else {
return "car is not running";
}
}

When “Car” is instantiated within another “Hello” class, the default constructor of Car class gets
invoked and initialized all the variables.
public class Hello {
public static void main(String[] args) {
Car car = new Car();
//calling the function
System.out.println(car.run());

Output
car is running
Parameterized Constructor – Constructor which accepts the parameters is called the parameterized
constructor. By using the parameterized constructor, you can provide values to variables during
instantiating the class.
You can generate parameterized constructor from the toolbar menu:

Source >> Generate Constructor using fields


Select the field or methods for which you want to generate the parameterized constructor.

Parameterized constructor example

public class Car {

private String doors;


private String engine;
private String driver;
private int speed;
 
//Parameterized constructor
public Car(String doors, String engine, String driver, int speed) {
this.doors = doors;
this.engine = engine;
this.driver = driver;
this.speed = speed;
}
 
public String run() {
if(doors.equals("closed") && engine.equals("on")&& driver.equals("seated")
&& speed >0) {
return "car is running";
}else {
return "car is not running";
}
}

In this program Value to the variables is provided during object creation of the class.
public class Hello {
public static void main(String[] args) {
Car car = new Car("closed","on", "seated", 10 );
//calling the function
System.out.println(car.run());

}
}
Output
car is running

In Java, when you do not have any constructor in the class, so during execution Java compiler adds
one constructor in the class, it is called as default constructor.

The default constructor does not have any parameters. The default constructor is used to providing
the default value to instance variables.

Default Constructor added by JVM


In the following example, In Smartphone class we do not write any constructor so JVM will add a
default constructor in the class and properties of the Smartphone class will be initialized using this
default constructor.

public class Smartphone {


private String brand = "Samsung";
 
public String getBrand() {
return brand;
}

As soon as we create the object of Smartphone class using the new keyword, the default
constructor of the class is invoked.
public class Hello {
 
public static void main(String[] args) {
Smartphone phone = new Smartphone();
        System.out.println(phone.getBrand());
}
 
}
Output:

Samsung

Default constructor added by User


In the following example, we will add a default constructor in Smartphone class.

public class Smartphone {


private String brand;
public Smartphone(String ibrand) {
brand=ibrand;
}
public String getBrand() {
return brand;
}
Again we create the object of Smartphone class using the new keyword, the default constructor of
the class is invoked
ublic static void main(String[] args) {

Smartphone phone = new Smartphone (“Nokia”);


System.out.println (phone. GetBrand ());
}
Output:

Nokia

Understanding Inheritance

Inheritance
Inheritance is used to store information and manage the information in a hierarchical order. It is the
process of defining a new class based on an existing class where a child class acquires the
properties of the parent class. The subclass (Child/Derived class) inherits the properties of the
ParentClass, and the class from which the properties are inherited is called a Super Class (Parent
class or Base class).

Inheritance allows us to reuse of code and improve the reusability in Java application so that a class
has to write only the unique features and rest of the common properties and functionality can be
extended by the other class.

Terminology
Super Class- Superclass is a class whose properties and behaviour are used by the child class.
Sub Class- Subclass is a class that inherits the properties of another class.
Reusability- Inheritance allows the reuse of code. When we create a new class and there is already
a class that includes some common properties or feature that a class has to write. It can be driven to
the new class from the existing class by reusing the field and method.
Extend Keyword
Extend keywords are used to inherit the properties of the class.

In the following example, we are demonstrating Java inheritance.  In this example, you can observe

When an object to Bike, Car, and Truck class is created, a copy of the contents of the superclass
(Vehicle) is made within it. That is why using the object of the subclass you can access the members
of a superclass.
The Superclass is a reference variable used to hold the subclass object. Reference variable allows
you access only the members of the superclass, for accessing the members of subclasses it is
recommended to always create a reference variable to the subclass. In this scenario, you may notice
that each child has exactly one parent this is known as single inheritance. Single inheritance doesn’t
prevent parents from having multiple children.
Note: The advantage of Inheritance is that the code that already exists code in a superclass can be reused
in sub/derived class.
Working with Inheritance
 Eclipse: Oxygen
 Java: 1.8

Inheritance
Inheritance is the process of defining a new class based on an existing class where a child class
acquires the properties of the parent class. For using the properties of a class (superclass) we need
to create a class(subclass) and then use the ‘extends’ keyword to use the common property in the
extended sub class. This is the basic functionality of inheritance to reduce the redundant code.

Extend Keyword
Extend keyword is used to inherit the properties of the class.

Let us consider the following program that demonstrates that inherits some properties and methods
in child class from the parent class.

 
Step 1: Let us create a class vehicle where we declare and define common properties and
methods. Here, vehicle is a super-class.

public class Vehicle {


public String engine;
public int wheels;
public int seats;
public int fueTank;
public String lights;
 
}

Step 2: We create a child class for example Bike, Car, Truck class which extends the above
class Vehicle. Here all these classes use specific properties. You can observe these specific
properties in blow statement.
Bike class

public class Bike extends Vehicle  {


public String handle;
}

Car class
public class Car extends Vehicle {
public String steering;
public String musicSystem;
public String airConditioner;
public String fridge;
public String entertainmentSystem;
}
Truck class
public class Truck extends Vehicle {
public String steering;
public String musicsystem;
public String airConditioner;
public String container;
}

Step 3: We create a class called Demo for creating an object of Bike class and initialize the variable
with string “short”.
public class Demo {
public static void main(String[] args) {
Bike bike = new Bike();
bike.handle = "short";
}

Step 4: We can access the methods from super-class in the sub-class as if they are in the same
class. e.g We create an object of bike class, which access the engine property of vehicle class.
public class Demo {
public static void main(String[] args) {
Bike bike = new Bike();
bike.handle = "short";
bike.engine = "Petrol";
System.out.println(bike.engine);
}
 
}

Output
Petrol

We have defined the properties. Now we will learn how default constructors of Superclass are called
automatically in the Subclass. Here in this post, we will learn how to inherit default constructor from
superclass to subclass.

For example, let’s return to the Vehicle example we used in the previous section and show two
related classes that define the same method:

We define the String property “lights” as private in the parent class Vehicle. However, when I display
the property lights without initializing and run the program we will receive an exception. I am not
allowed to define “lights” as public. Why?  Because lights entities are the private entities we won’t
access this private entity in the child class.

public class Vehicle {


public String engine;
public int wheels;
public int seats;
public int fueTank;
private String lights;
 
}

Exception in thread “main” java.lang.Error: Unresolved compilation problem:


      The field Vehicle.lights is not visible
     at org.studyeasy.Demo.main(Demo.java:11)

Access the private variables in the child class


In the following code, to access the private variables in java. We have provided a default constructor
and parameterize constructor. In default constructor, we have initialized some default properties.
You can provide public getter and setter methods to access or change the value of the private
member variables. In the following example, we have already initialized the default value so no need
to provide setter we will provide the only getter. So we are able to access the private method from
the parent class.

Vehicle Class

public class Vehicle {


private String engine;
private int wheels;
private int seats;
private int fuelTank;
private String lights;

public Vehicle() {
this.engine = "petrol";
this.wheels = 4;
this.seats = 4;
this.fueTank = 35;
this.lights = "LED";
 
}
 
public Vehicle(String engine, int wheels, int seats, int fuelTank, String lights) {
 
this.engine = engine;
this.wheels = wheels;
this.seats = seats;
this.fueTank = fueTank;
this.lights = lights;
}
 
public String getEngine() {
return engine;
}
 
public int getWheels() {
return wheels;
}
 
public int getSeats() {
return seats;
}
 
public int getFueTank() {
 
return fueTank;
}
 
public String getLights() {
return lights;
}
 
}
Bike Class
We have initialized the “handle” property in the default constructor. By using super keyword we
called the default constructor of parent (Vehicle) class.

public class Bike extends Vehicle {


private String handle;
 
public Bike() {
super();
this.handle = "short";
}
 
public Bike(String handle) {
super();
this.handle = handle;
}
 
public String getHandle() {
return handle;
}
 
}
Demo Class
By accessing the getHandle() and getEngine() method we display the properties values of bike
class.

public static void main(String[] args) {


 
Bike bike = new Bike();
System.out.println(bike.getHandle());
System.out.println(bike.getEngine());
 
}
 
}
Output:

short

petrol

  Note: In this program, we are making use of default constructor. In the next tutorial, we will make use of
the parameterized constructor.
We have learned how the default constructors of Superclass are called automatically in the
Subclass. Here, we will learn how to derive parameterized constructor from superclass to subclass.

public class Demo {


public static void main(String[] args) {
Bike bike = new Bike();
 
System.out.println("Handle: " + bike.getHandle());
System.out.println("Engine type: " + bike.getEngine());
 
}
 
}
Output
Handle: short

Engine type: petrol

Parent class parameterized constructor is called in child class using super ().super () should be the
written in the first line inside the constructor. For example, the output of the following program is:
public class Vehicle {
private String engine;
private int wheels;
private int seats;
private int fuelTank;
private String lights;
 
public Vehicle() {
this.engine = "petrol";
this.wheels = 4;
this.seats = 4;
this.fuelTank = 35;
this.lights = "LED";
 
}
public Vehicle(String engine, int wheels, int seats, int fuelTank, String lights) {
 
this.engine = engine;
this.wheels = wheels;
this.seats = seats;
this.fuelTank = fueTank;
this.lights = lights;
}
 
public String getEngine() {
return engine;
}
 
public int getWheels() {
return wheels;
}
 
public int getSeats() {
return seats;
}
 
public int getFueTank() {
return fuelTank;
}
 
public String getLights() {
return lights;
}
 
}
private String steering;
private String musicSystem;
private String airConditioner;
private String fridge;
private String entertainmentSystem;
public Car() {
super();
this.steering = "Power Steering";
}
public Car(String steering, String engine, int wheels, int seats, int fueTank, String lights) {
super(engine,wheels, seats,fueTank,lights);
this.steering = steering;
}
public String getSteering() {
return steering;
}
}
public class Demo {
public static void main(String[] args) {

  Car car = new Car("Power steering", "deisel", 4, 4, 40, "LED");

System.out.println("Steering: "+car.getSteering());
System.out.println("Engine type: "+car.getEngine());
System.out.println("Number of seats: "+car.getSeats());
System.out.println("Fuel tank capacity: "+car.getFueTank());
System.out.println("Head lamp type: "+car.getLights());
System.out.println("Number of wheels: "+car.getWheels());
}
 
}
Output:

Steering: Power steering

Engine type: Deisel

Number of seats: 4

Fuel tank capacity: 40

Headlamp type: LED

Number of wheels: 4

Java toString() method  


In Java toString() method is used to get a String representation of an object.

We can override the object’s toString() method during implementation.  The toString() method of the
Object class helps us to return values of the object, so we don’t need to write much code.

Example
In the following example, We have initialized the properties of Car using the constructor, printing the
object of the car class prints the hashCode (org.studyeasy.vehicles.Car@15db9742) values of the
objects.

public class Demo {


public static void main(String[] args) {
 
Car car = new Car("Power steering", "diesel", 4, 4, 40, "LED");
 
System.out.println(car);
}
}
public class Car extends Vehicle {
private String steering;
private String musicSystem;
private String airConditioner;
private String fridge;
private String entertainmentSystem;
 
public Car() {
super();
this.steering = "Power Steering";
}
 
public Car(String steering, String engine, int wheels, int seats, int fueTank, String lights) {
super(engine, wheels, seats, fueTank, lights);
this.steering = steering;
}
 
public String getSteering() {
return steering;
}
Output
org.studyeasy.vehicles.Car@15db9742

Let’s see the real example of toString () method in following code. We override the toString ()
method with the properties that we want to display.

public class Car extends Vehicle {


private String steering;
private String musicSystem;
private String airConditioner;
private String fridge;
private String entertainmentSystem;
 
public Car() {
super();
this.steering = "Power Steering";
}
 
public Car(String steering, String engine, int wheels, int seats, int fueTank, String lights) {
super(engine, wheels, seats, fueTank, lights);
this.steering = steering;
}
 
public String getSteering() {
return steering;
}
 
@Override
public String toString() {
return "Car [getSteering()=" + getSteering() + ", getEngine()=" + getEngine() + ", getWheels()=" +
getWheels()
+ ", getSeats()=" + getSeats() + ", getFueTank()=" + getFueTank() + ", getLights()=" +
getLights()
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" +
super.toString()
+ "]";
}
 
}
Output
Car [getSteering()=Power steering, getEngine()=deisel, getWheels()=4, getSeats()=4,
getFueTank()=40, getLights()=LED, getClass()=class org.studyeasy.vehicles.Car,
hashCode()=366712642, toString()=org.studyeasy.vehicles.Car@15db9742]

We have discussed superclasses and subclasses. Now, we will discuss method overriding.

Method overriding
The method override is used for the runtime polymorphism. It helps to define a behavior that is
specific to the subclass or child class type, which means a subclass can implement a parent class
based on your request.

Rules for Java Method Overriding


 The method must have the same name as in the parent class
 The method must be IS-A relationship(inheritance)
 The method must have the same parameters as in the parent class.
In the following example we demonstrate method overriding, the run () method of Parent class is
defined in child class with the same implementation, so output will be “Running vehicle”

public class Vehicle {


private String engine;
private int wheels;
private int seats;
private int fueTank;
private String lights;

 
public Vehicle() {
this.engine = "petrol";
this.wheels = 4;
this.seats = 4;
this.fueTank = 35;
this.lights = "LED";
 
}
 
public Vehicle(String engine, int wheels, int seats, int fuelTank, String lights) {
 
this.engine = engine;
this.wheels = wheels;
this.seats = seats;
this.fueTank = fueTank;
this.lights = lights;
}
 
public String getEngine() {
return engine;
}
 
public int getWheels() {
return wheels;
}
 
public int getSeats() {
return seats;
}
 
public int getFueTank() {
return fueTank;
}
 
public String getLights() {
return lights;
}
public void run() {
System.out.println( "Running vehicle");
}
}
public class Demo {
public static void main(String[] args) {
 
Car car = new Car("Power steering", "deisel", 4, 4, 40, "LED");
 
System.out.println(car);
car.run();
}
}
Output
Car [getSteering()=Power steering, getEngine()=deisel, getWheels()=4, getSeats()=4,
getFueTank()=40, getLights()=LED, getClass()=class org.studyeasy.vehicles.Car,
hashCode()=366712642, toString()=org.studyeasy.vehicles.Car@15db9742]

Running vehicle

In the following example, we have defined the run method in the child class, as defined in the parent
class but child class wants to specify its own implementation. The name of the method and
parameter must be the same and there must be an IS-A relationship between the classes.
Therefore, there is method overriding. When we execute this method, it generates “Running car”
instead of “Running vehicle”.

public class Car extends Vehicle {


private String steering;
private String musicSystem;
private String airConditioner;
private String fridge;
private String entertainmentSystem;

public Car() {
super();
this.steering = "Power Steering";
}
 
public Car(String steering, String engine, int wheels, int seats, int fuelTank, String lights) {
super(engine, wheels, seats, fueTank, lights);
this.steering = steering;
}
 
public String getSteering() {
return steering;
}
 
@Override
public String toString() {
return "Car [getSteering()=" + getSteering() + ", getEngine()=" + getEngine() + ", getWheels()=" +
getWheels()
+ ", getSeats()=" + getSeats() + ", getFueTank()=" + getFueTank() + ", getLights()=" +
getLights()
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" +
super.toString()
+ "]";
}
public void run() {
System.out.println("Running car");
System.out.println(toString());
}
}
public class Demo {
public static void main(String[] args) {
 
Car car = new Car("Power steering", "deisel", 4, 4, 40, "LED");
 
car.run();
}
}
Output
Running car

Car [getSteering()=Power steering, getEngine()=deisel, getWheels()=4, getSeats()=4,


getFueTank()=40, getLights()=LED, getClass()=class org.studyeasy.vehicles.Car,
hashCode()=366712642, toString()=org.studyeasy.vehicles.Car@15db9742]

Composition
The composition is the core concept of object-oriented programming. The composition is the design
technique to implement has-a relationship between different types of object/classes. We can use
Java inheritance or object composition in Java for code reuse.

Difference between inheritance and composition?


In Java, Inheritance is suitable only when classes are in a relationship. For example Car, Truck Bike
are a vehicle and all these vehicles have common features of vehicle class (Superclass). But to
represent engine relationship, we have an alternative to inheritance known as composition.

In inheritance, we can derive some functionality to a subclass of the parent class, in the composition
a class reuses the functionality by creating a reference to the object of the class.

For example, A laptop is a composite object containing other objects such as Screen, processor,
Ram, Hard drive, Graphics card, Optical drive, and Keyboard. In other words, the laptop object
shares a HAS-A relationship with other objects. The laptop is a composition which consists of
multiple components and works together as a team to solve a problem. Following components can
be simple as well as complex.
In the following list, Screen, RAM, Hard drive, optical drive Keyboard are simple composition.

 Screen -> Full HD/HD


 Ram-> DDR1/DDR2/DDR3/DDR4
 Hard drive-> 500 GB/1 TB/ 2TB
 Optical drive-> Single layer/multilayer
 Keyboard-> backlit/standard
Processor and graphics card are complex components. There are multiple things involved.

Processor
 Brand
 Series
 Generation
 No of Cores
 No of threads
 Cache memory
 Frequency
Graphics card
 Brand
 Series
 Memory
Composition setting up
In inheritance, we deal with the attributes of other classes. Composition studies have a relationship
in which we ‘inherit’ or use objects from other classes.

In the following example, Laptop HAS-A Processor which may have many features. Therefore, we
inherit the object and then access the attributes through these objects.

public class Laptop {

private float screen;

private Processor processor;

private String ram;

private String hardDrive;

private GraphicsCard graphicsCard;

private String opticalDrive;

private String keyboard;

public Laptop() {

this.screen = 15.6f;

this.processor = new Processor();

this.ram = "DDR4";

this.hardDrive = "2TB";

this.graphicsCard = new GraphicsCard();

this.opticalDrive = "MLT layer";

this.keyboard = "backlit";

public Laptop(float screen, Processor processor, String ram, String hardDrive, GraphicsCard
graphicsCard,
String opticalDrive, String keyboard) {

super();

this.screen = screen;

this.processor = processor;

this.ram = ram;

this.hardDrive = hardDrive;

this.graphicsCard = graphicsCard;

this.opticalDrive = opticalDrive;

this.keyboard = keyboard;

@Override

public String toString() {

return "Laptop [screen=" + screen + ", processor=" + processor + ", ram=" + ram + ",
hardDrive=" + hardDrive

+ ", graphicsCard=" + graphicsCard + ", opticalDrive=" + opticalDrive + ",


keyboard=" + keyboard + "]";

private String brand;

private int series;

private String memory;

public GraphicsCard() {

this.brand = "Nvidia";

this.series = 940;

this.memory = "2 GB";

}
public GraphicsCard(String brand, int series, String memory) {

this.brand = brand;

this.series = series;

this.memory = memory;

@Override

public String toString() {

return "GraphicsCard [brand=" + brand + ", series=" + series + ", memory=" + memory +
"]";

private String brand;

private String series;

private int generation;

private int cores;

private int threads;

private String cacheMemory;

private String frequency;

private String minFrequency;

private String maxfrequency;

public Processor() {

this.brand = "intel";

this.series = "i5 7200u";

this.generation = 7;

this.cores = 2;

this.threads = 4;
this.cacheMemory = "3MB";

this.frequency = "2.5Ghz";

this.minFrequency = "2.5Ghz";

this.maxfrequency = "3.1Ghz";

public Processor(String brand, String series, int generation, int cores, int threads, String
cacheMemory,

String frequency, String minFrequency, String maxfrequency) {

this.brand = brand;

this.series = series;

this.generation = generation;

this.cores = cores;

this.threads = threads;

this.cacheMemory = cacheMemory;

this.frequency = frequency;

this.minFrequency = minFrequency;

this.maxfrequency = maxfrequency;

@Override

public String toString() {

return "Processor [brand=" + brand + ", series=" + series + ", generation=" + generation
+ ", cores=" + cores

+ ", threads=" + threads + ", cacheMemory=" + cacheMemory + ",


frequency=" + frequency

+ ", minFrequency=" + minFrequency + ", maxfrequency=" +


maxfrequency + "]";
}

public static void main(String[] args) {

Laptop lappy = new Laptop();

System.out.println(lappy);

}
Output
Laptop [screen=15.6, processor=Processor [brand=intel, series=i5 7200u, generation=7, cores=2,
threads=4, cacheMemory=3MB, frequency=2.5Ghz, minFrequency=2.5Ghz,
maxfrequency=3.1Ghz], ram=DDR4, hardDrive=2TB, graphicsCard=GraphicsCard [brand=Nvidia,
series=940, memory=2 GB], opticalDrive=MLT layer, keyboard=backlit]

Working with composition


As we discussed, the classes inherit the objects of other classes. Hence to access the attributes we
need to create the getters to return the object of the classes by the virtue of which we can access
the required attribute.

public class Laptop {

private float screen;

private Processor processor;

private String ram;

private String hardDrive;

private GraphicsCard graphicsCard;

private String opticalDrive;

private String keyboard;

public Laptop() {

this.screen = 15.6f;

this.processor = new Processor();

this.ram = "DDR4";

this.hardDrive = "2TB";

this.graphicsCard = new GraphicsCard();


this.opticalDrive = "MLT layer";

this.keyboard = "backlit";

public Laptop(float screen, Processor processor, String ram, String hardDrive, GraphicsCard
graphicsCard,

String opticalDrive, String keyboard) {

this.screen = screen;

this.processor = processor;

this.ram = ram;

this.hardDrive = hardDrive;

this.graphicsCard = graphicsCard;

this.opticalDrive = opticalDrive;

this.keyboard = keyboard;

@Override

public String toString() {

return "Laptop [screen=" + screen + ", processor=" + processor + ", ram=" + ram + ",
hardDrive=" + hardDrive

+ ", graphicsCard=" + graphicsCard + ", opticalDrive=" + opticalDrive + ",


keyboard=" + keyboard + "]";

public Processor getProcessor() {

return processor;

public float getScreen() {

return screen;
}

public String getRam() {

return ram;

public String getHardDrive() {

return hardDrive;

public GraphicsCard getGraphicsCard() {

return graphicsCard;

public String getOpticalDrive() {

return opticalDrive;

public String getKeyboard() {

return keyboard;

public class GraphicsCard {

private String brand;

private int series;

private String memory;


public GraphicsCard() {

this.brand = "Nvidia";

this.series = 940;

this.memory = "2 GB";

public GraphicsCard(String brand, int series, String memory) {

this.brand = brand;

this.series = series;

this.memory = memory;

@Override

public String toString() {

return "GraphicsCard [brand=" + brand + ", series=" + series + ", memory=" + memory +
"]";

public class Processor {

private String brand;

private String series;

private int generation;

private int cores;

private int threads;

private String cacheMemory;

private String frequency;


private String minFrequency;

private String maxfrequency;

public Processor() {

this.brand = "intel";

this.series = "i5 7200u";

this.generation = 7;

this.cores = 2;

this.threads = 4;

this.cacheMemory = "3MB";

this.frequency = "2.5Ghz";

this.minFrequency = "2.5Ghz";

this.maxfrequency = "3.1Ghz";

public Processor(String brand, String series, int generation, int cores, int threads, String
cacheMemory,

String frequency, String minFrequency, String maxfrequency) {

this.brand = brand;

this.series = series;

this.generation = generation;

this.cores = cores;

this.threads = threads;

this.cacheMemory = cacheMemory;

this.frequency = frequency;

this.minFrequency = minFrequency;

this.maxfrequency = maxfrequency;
}

@Override

public String toString() {

return "Processor [brand=" + brand + ", series=" + series + ", generation=" + generation
+ ", cores=" + cores

+ ", threads=" + threads + ", cacheMemory=" + cacheMemory + ",


frequency=" + frequency

+ ", minFrequency=" + minFrequency + ", maxfrequency=" +


maxfrequency + "]";

public String getBrand() {

return brand;

public String getSeries() {

return series;

public int getGeneration() {

return generation;

public int getCores() {

return cores;

public int getThreads() {

return threads;
}

public String getCacheMemory() {

return cacheMemory;

public String getFrequency() {

return frequency;

public String getMinFrequency() {

return minFrequency;

public String getMaxfrequency() {

return maxfrequency;

public class Hello {

public static void main(String[] args) {

Laptop lappy = new Laptop();

System.out.println(lappy.getProcessor().getBrand());

}
}
Output

intel

Adding functionality
This tutorial deals with describing various functionalities of Composition. As described earlier in
composition we can ‘inherit’ objects which are used to reference the method or the attribute related
to the class.
The same concept is described here when the attributes of processor class are accessed by the
Demo class via Laptop.

public class Laptop {

private float screen;

private Processor processor;

private String ram;

private String hardDrive;

private GraphicsCard graphicsCard;

private String opticalDrive;

private String keyboard;

public Laptop() {
this.screen = 15.6f;

this.processor = new Processor();

this.ram = "DDR4";

this.hardDrive = "2TB";

this.graphicsCard = new GraphicsCard();

this.opticalDrive = "MLT layer";

this.keyboard = "backlit";

public Laptop(float screen, Processor processor, String ram, String hardDrive, GraphicsCard
graphicsCard,

String opticalDrive, String keyboard) {

this.screen = screen;

this.processor = processor;

this.ram = ram;

this.hardDrive = hardDrive;

this.graphicsCard = graphicsCard;

this.opticalDrive = opticalDrive;

this.keyboard = keyboard;

@Override

public String toString() {

return "Laptop [screen=" + screen + ", processor=" + processor + ", ram=" + ram + ",
hardDrive=" + hardDrive

+ ", graphicsCard=" + graphicsCard + ", opticalDrive=" + opticalDrive + ",


keyboard=" + keyboard + "]";

}
public Processor getProcessor() {

return processor;

public float getScreen() {

return screen;

public String getRam() {

return ram;

public String getHardDrive() {

return hardDrive;

public GraphicsCard getGraphicsCard() {

return graphicsCard;

public String getOpticalDrive() {

return opticalDrive;

public String getKeyboard() {

return keyboard;

public String gamingMode(){

processor.setFrequency(processor.getMaxfrequency());
return "Success";

public class Processor {

private String brand;

private String series;

private int generation;

private int cores;

private int threads;

private String cacheMemory;

private String frequency;

private String minFrequency;

private String maxfrequency;

public Processor() {

this.brand = "intel";

this.series = "i5 7200u";

this.generation = 7;

this.cores = 2;

this.threads = 4;

this.cacheMemory = "3MB";

this.frequency = "2.5Ghz";

this.minFrequency = "2.5Ghz";

this.maxfrequency = "3.1Ghz";

}
public Processor(String brand, String series, int generation, int cores, int threads, String
cacheMemory,

String frequency, String minFrequency, String maxfrequency) {

this.brand = brand;

this.series = series;

this.generation = generation;

this.cores = cores;

this.threads = threads;

this.cacheMemory = cacheMemory;

this.frequency = frequency;

this.minFrequency = minFrequency;

this.maxfrequency = maxfrequency;

@Override

public String toString() {

return "Processor [brand=" + brand + ", series=" + series + ", generation=" + generation
+ ", cores=" + cores

+ ", threads=" + threads + ", cacheMemory=" + cacheMemory + ",


frequency=" + frequency

+ ", minFrequency=" + minFrequency + ", maxfrequency=" +


maxfrequency + "]";

public String getBrand() {

return brand;

public String getSeries() {


return series;

public int getGeneration() {

return generation;

public int getCores() {

return cores;

public int getThreads() {

return threads;

public String getCacheMemory() {

return cacheMemory;

public String getFrequency() {

return frequency;

public String getMinFrequency() {

return minFrequency;

public String getMaxfrequency() {

return maxfrequency;
}

public void setFrequency(String frequency) {

this.frequency = frequency;

public class Hello {

public static void main(String[] args) {

//Laptop lappy = new Laptop();


//System.out.println(lappy.getProcessor().getBrand());

Processor processor = new Processor("intel", "7200U", 7, 4, 4, "6MB"

+ "", "2.5Ghz", "2.5Ghz", "3.1Ghz");

GraphicsCard graphicsCard = new GraphicsCard("Nvidia", 1050, "4GB");

Laptop gamingLaptop = new Laptop(17f, processor,

"DDR4", "2TB", graphicsCard, null, "backlit");

System.out.println(gamingLaptop);

gamingLaptop.gamingMode();

System.out.println("Gaming mode on");

System.out.println("Current frequency: "+gamingLaptop.getProcessor().getFrequency());

}Output
Laptop [screen=17.0, processor=Processor [brand=intel, series=7200U, generation=7, cores=4,
threads=4, cacheMemory=6MB, frequency=2.5Ghz, minFrequency=2.5Ghz,
maxfrequency=3.1Ghz], ram=DDR4, hardDrive=2TB, graphicsCard=GraphicsCard [brand=Nvidia,
series=1050, memory=4GB], opticalDrive=null, keyboard=backlit]

Gaming mode on

Current frequency: 3.1Ghz

Attacjed is the java files used for testing.

You might also like