By default all class in java are

What is a Class in Java with Example

A Class can be defined as a template / blueprint for creating objects which defines its state and behavior. Class can have three major components such as variables,methods and constructors. We can create a class with all of these components or some of these or even none of these, but a class with no components is of no use. Lets take a look into the exo-skeleton of declaring a class first

Class in Java syntax:

> class > extends > implements ><>
  • Access specifier : Allowable Access specifier for a class are public and default. Access specifiers defines the range of a class where it can be accessed. If a class is public then it can be accessed from anywhere. If you have not added anything in front of a class then it is called as default access specifier. Default access falls between protected and private access, allowing only classes in the same package to access.
  • class keyword : The access specifier is followed by class keyword which symbolizes that this entity is a class.
  • Class Name : The class keyword is followed by a class name, which follows the rules of identifiers
  • Extending & Implement : A class can extends only 1 other class, whereas it can implement any number of interfaces.
Читайте также:  Как обновить php reg ru

Rules for declaring a class in Java

  1. A class can have only public or default access specifier, no other access specifier ( protected, private) can be applied to a class.
  2. default access can be seen only by classes within the same package
  3. Only abstract, static, final non-access modifiers can be applied to a class.
  4. An abstract class in Java can not be instantiated. It can have both abstract methods and concrete methods
  5. A final class in Java can not be sub-classed but object can be created for it.
  6. It must have the class keyword, and class must be followed by a legal identifier.
  7. All classes will be by default extending Java Object class( java.lang.Object ), in addition to it all the classes can extends one other class ( only one class ).
  8. It can implement any number of java interfaces each interface has to be separated by a comma.
  9. All the variables, methods, and constructors should be defined within the java class only.
  10. Each .java source file may contain only one public class. and can have any number of other visible classes.
  11. The source file name must match the public class name and it must have a .java suffix.

Variables in a class :

A class can have the following variable types inside it.

  • Local Variables : Local Variables are the variables which are defined within the methods or constructors. Those type of variables will be initialized with in the method and will get destroyed once the execution of the method is completed.
public class Class_Example < public Class_Example() < String value = "Test";// Local Variable inside a Constructor >public void disp() < String name = "JavaInterviewPoint";// Local variable inside method System.out.println("Welcome " + name + ". "); >>
  • Instance Variables : Instance Variables are the one which is defined outside of methods or constructors. These variables get initialized when the class is instantiated and can be called only with the help of objects. These variables can be accessed within any method or constructor.
public class Class_Example < String name = "JavaInterviewPoint";//Defining a Instance Variable public Class_Example() < //Using the Instance variable inside a constructor System.out.println("Welcome " + name + ". "); >public void disp() < //Using the Instance variable inside a method System.out.println("Welcome " + name + ". "); >>
  • Class Variables :Class Variables is almost similar to Instance variable except it has a static keyword in the front indicating the variable belongs to the java class and not to any instance. A class variable can be called directly with the class name like >.>
public class Class_Example < static String name = "JavaInterviewPoint";//Defining a Class Variable public Class_Example() < //Using the Class variable inside a constructor System.out.println("Welcome " + Class_Example.name + ". "); >public void disp() < //Using the Instance variable inside a method System.out.println("Welcome " + Class_Example.name + ". "); >>

Java class Constructor :

This is the second most important topic which comes into mind when we speak about a class. Every class will be having a constructor either we have to define it explicitly or the compiler will create a default constructor for you. A class can have any number of constructors. Every time when a new instance is created for the class the constructor will be called, the main rule here is that constructor name for a java class should be the same name of the class name and should not have any return type.

public class Class_Example < static String name = "JavaInterviewPoint";//Defining a Class Variable //Default Constructor public Class_Example() < >//Parameterized Constructor public Class_Example(String name) < this.name=name; >>

Example of Class in Java

Lets create a real world example class “BMWCar” putting all the above learnt concepts.

Читайте также:  Java android listview адаптер

We have a “Vehicle” interface which consist of two methods numberOfWheels() and speedOfVehicle() both will be declared here and the body will be given by BMWCar class.

“Car” is our super class here consisting of a simple carColor() method, the Car class will be extended by our BMWCar class.

Finally “BMWCar” class extends the “Car” class and implements “Vehicle” interface. In the main method we will be creating the object for the BMWCar and will be calling the individual methods.

public interface Vehicle < public void numberOfWheels(); public void speedOfVehcile(); >class car < public void carColor() < System.out.println("Color of the car is \"Blue\""); >> public class BMWCar extends car implements Vehicle < int wheels = 4;//instance variable public BMWCar() < System.out.println("Default Constructor called"); >@Override public void numberOfWheels() < System.out.println("BMW Car has \""+wheels+"\" wheels"); >@Override public void speedOfVehcile() < int speed = 50;//local variable System.out.println("BMW car is driving at \""+speed+"\" kmph"); >public static void main(String args[]) < //creating object for the child class BMWCar bmwCar = new BMWCar(); //Calling parent class method bmwCar.carColor(); //Calling child class methods bmwCar.numberOfWheels(); bmwCar.speedOfVehcile(); >>
Default Constructor called Color of the car is "Blue" BMW Car has "4" wheels BMW car is driving at "50" kmph

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java
  • Types of Inheritance in Java
  • Java does not supports Multiple Inheritance Diamond Problem?
Читайте также:  Удаление пустых строк массива php

Источник

Java Object Class Tutorial

java object class

Classes and objects in Java are the two most essential Java concepts that every programmer must learn. Classes and objects are closely related and work together. An object has behaviors and states, and is an instance of class. For instance, a cat is an object—it’s color and size are states, and its meowing and clawing furniture are behaviors. A class models the object, a blueprint or template that describes the state or behavior supported by objects of that type.

What is Class In Java?

A class is a blueprint for the object. Before we create an object, we first need to define the class.

We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can create many objects from a class.

How to Create a Class In Java?

We can define a typical class in Java using the following syntax:

public class Student < String Name; int rollno; String section; void study() < >void write() < >void play() < >>

Object

It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical object class Java program creates many objects, which as you know, interact by invoking methods. An object consists of :

🡪State: It is represented by attributes of an object. It also reflects the properties of an object.

🡪Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.

🡪Identity: It gives a unique name to an object and enables one object to interact with other objects.

Example :

className object = new className(); // for Bicycle class Bicycle sportsBicycle = new Bicycle(); Bicycle touringBicycle = new Bicycle();

Access Modifier

Object-oriented programming languages like Java provide the programmers with four types of access modifiers.

These access modifiers specify the accessibility and users permissions of the methods and members of the class.

Rules for Creating Classes

The following rules are mandatory when you’re working with Java classes:

  • The keyword “class” must be used to declare a class
  • Every class name should start with an upper case character, and if you intend to include multiple words in a class name, make sure you use the camel case
  • A Java project can contain any number of default classes but should not hold more than one public class
  • You should not use special characters when naming classes
  • You can implement multiple interfaces by writing their names in front of the class, separated by commas
  • You should expect a Java class to inherit only one parent class

How to declare a Object in Java?

There are three major steps or points to be considered :-

Example:

public class Student < public Student (String name) < System.out.println("parameters sent are :" + name ); >public static void main(String []args) < Student mystudent = new Student( "Steven" ); >>

Output :

Java Class Object and Methods Example

In this example we will do a java class object program –

public class ClassInJava < String brand; String model; int modelno; //Constructor ClassInJava(String brand,String model,int modelno)< this.brand=brand; this.model=model; this.modelno=modelno; >public static void main(String[] args) < //Object of class ClassInJava ClassInJava object=new ClassInJava("Redmi" , "Redmi Note 13" ,1010); System.out.println("Mobile Brand is: " + object.brand); System.out.println("Mobile Model is: " + object.model); System.out.println("Mobile's Model No. is: "+ object.modelno); >>

Output :

Mobile Brand is: Redmi Mobile Model is: Redmi Note 13 Mobile’s Model No. is: 1010

Java Object Class is basically the parent class of all classes. In other words, it is the topmost class of java. By Default, It extends to every class of java. Object class comes under the java.lang package.

Lang package has included by default. If any Java class does not extend any other class then it is a direct child class of Object and if extends other class then it is indirectly derived. Therefore we can easily use all the methods of Object class. Object class has many inbuilt methods that we can use to fulfill the requirement. Check other Java Turorial and examples.

Object Class Declaration

public class java.lang.Object

Class Constructors

Object class has only one constructor.

Object Class Methods

Java Object class has many inbuilt methods. These methods are very commonly used in programming. But we do not know exactly which method belongs to Object Class. There are list of all methods of Object Class. In this tutorial, we will explain each and every method with example.

Parameters : Not Accept Any Parameter.
Return : Return the copy of this object.

2.) public boolean equals(Object oj)

Parameters : It accepts object which we want to compare.
Return : Return the boolean value true if given object matches otherwise it returns false.

3.) protected void finalize()

Garbage Collector calls this method. When garbage collection determines that there are no more references to the object. So this method automatically call and perform operation.

Parameters : No Parameters.
Return : NA.

4.) public final Class getClass()

Parameters : No Parameters.
Return : getClass() method returns the object of the class.

Java.lang.toString() method is very important and common used in Java. Because it converts any Object to String.

Parameters: NA
Return: This method will return the String representation of the Object.

Java.lang.Object.notify() method used in the Java Multithreading. But this method comes under the java.lang package. This method wakes up a single thread that is waiting on this object’s monitor. If many threads are waiting on this object, one of them is chosen to be awakened. So we can use this method.

Parameters: NA
Return: This method does not return anything. Because it has different functionality mentioned above.

We hope you like the post. If you have any doubt please comment below. So we can improve the content.

Fuel Your Passion for Coding: Dive into Our Other Posts

JavaScript Display None Property

Источник

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