GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||
GeezerVison is showing zetcode.com — Object-oriented programming in Java - OOP concepts Java Object-oriented programminglast modified January 27, 2024 In this article we cover object-oriented programming in Java. We mention Java objects, object attributes and methods, object constructors, and access modifiers. Furthermore, we talk about the super keyword, constructor chaining, class constants, inheritance, polymorphism, final classes, and private constructors. There are three widely used programming paradigms: procedural programming, functional programming, and object-oriented programming. Java is principally an object-oriented programming language. Since Java 8, it has some support of the functional programming. Object-oriented programmingObject-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. The following are basic programming concepts in OOP:
The abstraction is simplifying complex reality by modeling classes appropriate to the problem. The polymorphism is the process of using an operator or function in different ways for different data input. The encapsulation hides the implementation details of a class from other objects. The inheritance is a way to form new classes using classes that have already been defined. Java objectsObjects are basic building blocks of a Java OOP program. An object is a combination of data and methods. In an OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages, and process data. There are two steps in creating an object. First, we define a class. A class is a template for an object. It is a blueprint which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class. com/zetcode/SimpleObject.java
package com.zetcode;
class Being {}
public class SimpleObject {
public static void main(String[] args) {
Being b = new Being();
System.out.println(b);
}
}
In our first example, we create a simple object. class Being {}
This is a simple class definition. The body of the template is empty. It does not have any data or methods. Being b = new Being();
We create a new instance of the System.out.println(b);
We print the object to the console to get some basic description of the object.
What does it mean, to print an object? When we print an object, we in fact call
its $ javac com/zetcode/SimpleObject.java $ ls com/zetcode/ Being.class SimpleObject.class SimpleObject.java
The compiler creates two class files. The $ java com.zetcode.SimpleObject com.zetcode.Being@125ee71 We get a the name of the class of which the object is an instance, the @ character, and the unsigned hexadecimal representation of the hash code of the object. Java object attributesObject attributes is the data bundled in an instance of a class. The object attributes are called instance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy. com/zetcode/ObjectAttributes.java
package com.zetcode;
class Person {
public String name;
}
public class ObjectAttributes {
public static void main(String[] args) {
Person p1 = new Person();
p1.name = "Jane";
Person p2 = new Person();
p2.name = "Beky";
System.out.println(p1.name);
System.out.println(p2.name);
}
}
In the above Java code, we have a class Person {
public String name;
}
We declare a name member field. The Person p1 = new Person(); p1.name = "Jane";
We create an instance of the Person p2 = new Person(); p2.name = "Beky";
We create another instance of the System.out.println(p1.name); System.out.println(p2.name); We print the contents of the variables to the console. $ java com.zetcode.ObjectAttributes Jane Beky
We see the output of the program. Each instance of the Java methodsMethods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods bring modularity to our programs.
Methods are essential in the encapsulation concept of the OOP paradigm.
For example, we might have a Objects group state and behavior. Methods represent the behavioral part of the objects. com/zetcode/Methods.java
package com.zetcode;
class Circle {
private int radius;
public void setRadius(int radius) {
this.radius = radius;
}
public double area() {
return this.radius * this.radius * Math.PI;
}
}
public class Methods {
public static void main(String[] args) {
Circle c = new Circle();
c.setRadius(5);
System.out.println(c.area());
}
}
In the code example, we have a private int radius;
We have one member field in the class. It is the radius of the circle. The
public void setRadius(int radius) {
this.radius = radius;
}
This is the Circle c = new Circle(); c.setRadius(5);
We create an instance of the public double area() {
return this.radius * this.radius * Math.PI;
}
The $ java com.zetcode.Methods 78.53981633974483 Java access modifiers
Access modifiers set the visibility of methods and member fields.
Java has three access modifiers:
The Access modifiers protect data against accidental modifications. They make the programs more robust.
The above table summarizes Java access modifiers (+ is accessible, o is not accessible). com/zetcode/AccessModifiers.java
package com.zetcode;
class Person {
public String name;
private int age;
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
}
public class AccessModifiers {
public static void main(String[] args) {
Person p = new Person();
p.name = "Jane";
p.setAge(17);
System.out.println(String.format("%s is %d years old",
p.name, p.getAge()));
}
}
In the above program, we have two member fields: public and private. public int getAge() {
return this.age;
}
If a member field is private, the only way to access it is via methods. If we
want to modify an attribute outside the class, the method must be declared
public void setAge(int age) {
this.age = age;
}
The Person p = new Person(); p.name = "Jane";
We create a new instance of the p.setAge(17);
The System.out.println(String.format("%s is %d years old",
p.name, p.getAge()));
Finally, we access both members to build a string, which is printed to the console. $ java com.zetcode.AccessModifiers Jane is 17 years old Running the example we have this output. The following program shows how access modifiers influence the way members are inherited by subclasses. com/zetcode/ProtectedMember.java
package com.zetcode;
class Base {
public String name = "Base";
protected int id = 5323;
private boolean isDefined = true;
}
class Derived extends Base {
public void info() {
System.out.println("This is Derived class");
System.out.println("Members inherited:");
System.out.println(this.name);
System.out.println(this.id);
// System.out.println(this.isDefined);
}
}
public class ProtectedMember {
public static void main(String[] args) {
Derived drv = new Derived();
drv.info();
}
}
In this program, we have a class Derived extends Base {
The System.out.println(this.name); System.out.println(this.id); // System.out.println(this.isDefined);
The $ java com.zetcode.ProtectedMember This is Derived class Members inherited: Base 5323 Running the program, we receive this output. Java constructor
A constructor is a special kind of a method. It is automatically called when the
object is created. Constructors do not return values and also do not use the
Constructors cannot be inherited. They are called in the order of inheritance. If we do not write any constructor for a class, Java provides an implicit default constructor. If we provide any kind of a constructor, then the default is not supplied. com/zetcode/Constructor.java
package com.zetcode;
class Being {
public Being() {
System.out.println("Being is created");
}
public Being(String being) {
System.out.println(String.format("Being %s is created", being));
}
}
public class Constructor {
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String[] args) {
new Being();
new Being("Tom");
}
}
We have a Being class. This class has two constructors. The first one does not take parameters, the second one takes one parameter. public Being() {
System.out.println("Being is created");
}
This constructor does not take any parameters. public Being(String being) {
System.out.println(String.format("Being %s is created", being));
}
This constructor takes one string parameter. @SuppressWarnings("ResultOfObjectAllocationIgnored")
This annotation will suppress a warning that we do not assign our created objects to any variables. Normally this would be a suspicious activity. new Being();
An instance of the new Being("Tom");
Another instance of the $ java com.zetcode.Constructor Being is created Being Tom is created In the next example, we initiate data members of the class. Initiation of variables is a typical job for constructors. com/zetcode/MemberInit.java
package com.zetcode;
class User {
private String occupation;
private String name;
public User(String name, String occupation) {
this.name = name;
this.occupation = occupation;
}
public void info() {
System.out.format("%s is a %s\n", this.name, this.occupation);
}
}
public class MemberInit {
public static void main(String[] args) {
String name = "John Doe";
String occupation = "gardener";
User u = new User(name, occupation);
u.info();
}
}
We have a private String occupation; private String name; We have two private variables in the class definition. public User(String name, String occupation) {
this.name = name;
this.occupation = occupation;
}
In the constructor, we initiate the two data members. The User u = new User(name, occupation); u.info();
We create a $ java com.zetcode.MemberInit John Doe is a gardener Java super keyword
The com/zetcode/SuperVariable.java
package com.zetcode;
class Shape {
int x = 50;
int y = 50;
}
class Rectangle extends Shape {
int x = 100;
int y = 100;
public void info() {
System.out.println(x);
System.out.println(super.x);
}
}
public class SuperVariable {
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.info();
}
}
In the example, we refer to the parent's variable with the
public void info() {
System.out.println(x);
System.out.println(super.x);
}
Inside the If a constructor does not explicitly invoke a superclass constructor, Java automatically inserts a call to the no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, we get a compile-time error. com/zetcode/ImplicitSuper.java
package com.zetcode;
class Vehicle {
public Vehicle() {
System.out.println("Vehicle created");
}
}
class Bike extends Vehicle {
public Bike() {
// super();
System.out.println("Bike created");
}
}
public class ImplicitSuper {
public static void main(String[] args) {
Bike bike = new Bike();
System.out.println(bike);
}
}
The example demonstrates the implicit call to the parent's constructor. public Bike() {
// super();
System.out.println("Bike created");
}
We get the same result if we uncomment the line. $ java com.zetcode.ImplicitSuper Vehicle created Bike created com.zetcode.Bike@15db9742
Two constructors are called when a There can be more than one constructor in a class. com/zetcode/SuperCalls.java
package com.zetcode;
class Vehicle {
protected double price;
public Vehicle() {
System.out.println("Vehicle created");
}
public Vehicle(double price) {
this.price = price;
System.out.printf("Vehicle created, price %.2f set%n", price);
}
}
class Bike extends Vehicle {
public Bike() {
super();
System.out.println("Bike created");
}
public Bike(double price) {
super(price);
System.out.printf("Bike created, its price is: %.2f %n", price);
}
}
public class SuperCalls {
public static void main(String[] args) {
Bike bike1 = new Bike();
Bike bike2 = new Bike(45.90);
}
}
The example uses different syntax of super(); Here, we call the parent's no-argument constructor. super(price); This syntax calls the parent's constructor that takes one parameter: the bike's price. $ java com.zetcode.SuperCalls Vehicle created Bike created Vehicle created, price 45.90 set Bike created, its price is: 45.90 Java constructor chaining
Constructor chaining is the ability to call another constructor from a
constructor. To call another constructor from the same class, we use the
com/zetcode/ConstructorChaining.java
package com.zetcode;
class Shape {
private int x;
private int y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
protected int getX() {
return this.x;
}
protected int getY() {
return this.y;
}
}
class Circle extends Shape {
private int r;
public Circle(int r, int x, int y) {
super(x, y);
this.r = r;
}
public Circle() {
this(1, 1, 1);
}
@Override
public String toString() {
return String.format("Circle: r:%d, x:%d, y:%d", r, getX(), getY());
}
}
public class ConstructorChaining {
public static void main(String[] args) {
Circle c1 = new Circle(5, 10, 10);
Circle c2 = new Circle();
System.out.println(c1);
System.out.println(c2);
}
}
We have a class Shape {
private int x;
private int y;
...
}
The public Shape(int x, int y) {
this.x = x;
this.y = y;
}
The constructor of the protected int getX() {
return this.x;
}
protected int getY() {
return this.y;
}
We have defined two methods to retrieve the values of the coordinates. The members are private, so the only access possible is through methods. class Circle extends Shape {
private int r;
...
}
The public Circle(int r, int x, int y) {
super(x, y);
this.r = r;
}
The first constructor of the public Circle() {
this(1, 1, 1);
}
The second constructor takes no parameters. In such a case, we provide some
default values. The @Override
public String toString() {
return String.format("Circle: r:%d, x:%d, y:%d", r, getX(), getY());
}
Inside the $ java com.zetcode.ConstructorChaining Circle: r:5, x:10, y:10 Circle: r:1, x:1, y:1 Java class constantsIt is possible to create class constants. These constants do not belong to a concrete object. They belong to the class. By convention, constants are written in uppercase letters. com/zetcode/ClassConstant.java
package com.zetcode;
class Math {
public static final double PI = 3.14159265359;
}
public class ClassConstant {
public static void main(String[] args) {
System.out.println(Math.PI);
}
}
We have a public static final double PI = 3.14159265359;
The $ java com.zetcode.ClassConstant 3.14159265359 Running the example we get the above output. Java toString method
Each object has the com/zetcode/ThetoStringMethod.java
package com.zetcode;
class Being {
@Override
public String toString() {
return "This is Being class";
}
}
public class ThetoStringMethod {
public static void main(String[] args) {
Being b = new Being();
Object o = new Object();
System.out.println(o.toString());
System.out.println(b.toString());
System.out.println(b);
}
}
We have a @Override
public String toString() {
return "This is Being class";
}
Each class created inherits from the base Being b = new Being(); Object o = new Object(); We create two objects: one custom defined and one built-in. System.out.println(o.toString()); System.out.println(b.toString());
We call the System.out.println(b);
As we have specified earlier, placing an object as a parameter to the
$ java com.zetcode.ThetoStringMethod java.lang.Object@125ee71 This is Being class This is Being class This is what we get when we run the example. Inheritance in JavaInheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors). com/zetcode/Inheritance.java
package com.zetcode;
class Being {
public Being() {
System.out.println("Being is created");
}
}
class Human extends Being {
public Human() {
System.out.println("Human is created");
}
}
public class Inheritance {
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String[] args) {
new Human();
}
}
In this program, we have two classes: a base class Human extends Being {
In Java, we use the new Human();
We instantiate the derived $ java com.zetcode.Inheritance Being is created Human is created We can see that both constructors were called. First, the constructor of the base class is called, then the constructor of the derived class. A more complex example follows. com/zetcode/Inheritance2.java
package com.zetcode;
class Being {
static int count = 0;
public Being() {
count++;
System.out.println("Being is created");
}
public void getCount() {
System.out.format("There are %d Beings%n", count);
}
}
class Human extends Being {
public Human() {
System.out.println("Human is created");
}
}
class Animal extends Being {
public Animal() {
System.out.println("Animal is created");
}
}
class Dog extends Animal {
public Dog() {
System.out.println("Dog is created");
}
}
public class Inheritance2 {
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String[] args) {
new Human();
Dog dog = new Dog();
dog.getCount();
}
}
With four classes, the inheritance hierarchy is more complicated. The
static int count = 0;
We define a public Being() {
count++;
System.out.println("Being is created");
}
Each time the class Animal extends Being {
...
class Dog extends Animal {
...
The new Human(); Dog dog = new Dog(); dog.getCount();
We create instances from the $ java com.zetcode.Inheritance2 Being is created Human is created Being is created Animal is created Dog is created There are 2 Beings
The Java polymorphismPolymorphism is the process of using an operator or function in different ways for different data input. In practical terms, polymorphism means that if class B inherits from class A, it doesn't have to inherit everything about class A; it can do some of the things that class A does differently. In general, polymorphism is the ability to appear in different forms. Technically, it is the ability to redefine methods for derived classes. Polymorphism is concerned with the application of specific implementations to an interface or a more generic base class. Simply put, polymorphism is the ability to redefine methods for derived classes. com/zetcode/Polymorphism.java
package com.zetcode;
abstract class Shape {
protected int x;
protected int y;
public abstract int area();
}
class Rectangle extends Shape {
public Rectangle(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int area() {
return this.x * this.y;
}
}
class Square extends Shape {
public Square(int x) {
this.x = x;
}
@Override
public int area() {
return this.x * this.x;
}
}
public class Polymorphism {
public static void main(String[] args) {
Shape[] shapes = { new Square(5),
new Rectangle(9, 4), new Square(12) };
for (Shape shape : shapes) {
System.out.println(shape.area());
}
}
}
In the above program, we have an abstract @Override
public int area() {
return this.x * this.y;
}
...
@Override
public int area() {
return this.x * this.x;
}
The Shape[] shapes = { new Square(5),
new Rectangle(9, 4), new Square(12) };
We create an array of three shapes. for (Shape shape : shapes) {
System.out.println(shape.area());
}
We go through each shape and call the Final class, private constructor
A class with a FinalClass.java
package com.zetcode;
final class MyMath {
public static final double PI = 3.14159265358979323846;
// other static members and methods
}
public class FinalClass {
public static void main(String[] args) {
System.out.println(MyMath.PI);
}
}
We have a Furthermore, we also do not want to allow creation of instances from our class. We decide it to be used only from a static context. Declaring a private constructor, the class cannot be instantiated. com/zetcode/MyMath.java
package com.zetcode;
final class MyMath {
private MyMath() {}
public static final double PI = 3.14159265358979323846;
// other static members and methods
}
public class PrivateConstructor {
public static void main(String[] args) {
System.out.println(MyMath.PI);
}
}
Our SourceJava Object-Oriented Programming Concepts In this article we have covered object-oriented programming in Java. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Java tutorials. | ||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |