欢迎来到百战百胜!我们致力于为广大IT从业者、学生和爱好者提供全面、实用的资源和服务。加入我们的聊天群,这里有专业大佬为你提供有价值的建议和指导!

Java是世界上排名前两位的编程语言之一,这是有原因的--它拥有一些最强大和最有用的特性。就像Java中的OOPS概念。

Java中的OOPS概念主要集中在为数据成员提供有组织的和清晰的结构;以及以对象的形式在程序中提供操作方法。与过程性编程不同,革命性的面向对象编程方法将编程能力和功能提高到了指数级。

什么是class?

如前所述,面向对象编程中的类是以数据结构的形式存储数据成员和数据操作方法的蓝图。

要声明类,我们使用关键字class,后跟用户定义的名称。

Syntax:
<Access Modifier> class <name_of_the_class>{
 Data members;
 Data methods;
 Class Statements;
}

Example:
package tech.besthub;
import java.util.Scanner;
public class Area {
   public static void main (String[] args)
   {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the length of the Rectangle:");
    double l = scanner.nextDouble();
    System.out.println("Enter the breadth of the Rectangle:");
    double b = scanner.nextDouble();
    double a = l*b;
    System.out.println("Area of the given Rectangle is:"+a);
   }
}

static关键字

Java中的static关键字充当访问修饰符。当使用Static关键字声明特定的类、方法或变量时,则这些声明的项。被禁止修改或获得访问权限。它们的原始值和属性保持不变。

Syntax:
<access_modifier> static <name_of_the_class>;
static <data type> <name_of_the_variable>;
static <method_name>;

Example:
package tech.besthub;
class Employee {
 int E_ID;
 String name;
 static String Organisation = "XYZ-Org";
 Employee(int e_id, String N) {
  E_ID = e_id;
  name = N;
 }

 void display() {
  System.out.println(E_ID + " " + name + " " + Organisation);
 }
}

public class Static {
 public static void main(String args[]) {
  Employee e1 = new Employee(10432, "John");
  Employee e2 = new Employee(10483, "Anthony");
  Employee e3 = new Employee(10232, "Steve");
  Employee e4 = new Employee(10856, "Thomas");
  e1.display();
  e2.display();
  e3.display();
  e4.display();
 }
}

this关键字

术语“this”是Java中的一个关键字,它是指当前对象的引用变量。它根据它的要求在不同的地方使用。其中一些实施包括:

  • 从当前类调用方法

  • 从当前类调用构造函数

  • 引用当前类中的实例变量

  • 从方法返回当前类的实例

  • 将参数传递给方法或构造函数

Syntax:
this.<method_name>;
this.<variable_name>;

Example:
package tech.besthub;
class StudentData {
 int ID;
 String name;
 int rank;
 StudentData(int ID, String name, int rank) {
  this.ID = ID;
  this.name = name;
  this.rank = rank;
 }

 void display() {
  System.out.println(ID + " " + name + " " + rank);
 }
}

public class This {
 public static void main(String args[]) {
  StudentData student1 = new StudentData(8010, "sam", 18);
  StudentData student2 = new StudentData(8121, "Jennifer ", 3);
  student1.display();
  student2.display();
 }
}

什么是object?

对象是每种面向对象编程语言的构建块。对象是在使用特定类时创建的。对象可以包括属性和方法。有时,它还可能包括另一个对象。

Syntax:
<class_name> <object_name> = new <class_name>(“<parameters”);

Example:
Employee e1 = new Employee ("Sharon", 102030, "B+");

什么是构造器?

构造函数是将类用作蓝图的唯一方法。它初始化类对象并构造它们。

Syntax: 
<class_name> <object_name> = new <class_name>(“<parameters”);

Example:
Student s1 = new Student (“Jayson”, 22901, “First-Grade”);

什么是方法?

Java方法是用户定义他们想要应用到其数据成员的操作的位置。程序员在类内部定义方法。

Syntax:
<Access_Modifier> <Datatype> <Method_Name> (<Parameters>) {
 Return <Result>;
}

Example:
Public float sum(float x, float y) {
 return z=x+y;
}

Java中的OOPs概念

面向对象编程是构建软件的结构化方法。通过它,类是保存方法的构建蓝图,而对象是存储类实例的基本构建块。

在Java中,有四条法则定义了面向对象编程。它们包括:

  • 抽象 

  • 封装

  • 继承

  • 多态

Java面向对象概念中的抽象

abstraction.

在面向对象编程中,抽象使用户无法查看复杂方法的实现。换句话说,用户只能看到他们希望看到的必要细节和信息,并隐藏实现的不必要的复杂性。

在Java中,当包含以下特殊类时,可以实现抽象:

  • 接口类

  • 抽象类

Java中的接口

/interface

Java中的接口充当仅存储方法签名并排除数据成员及其方法定义的容器。使用接口降低了代码的复杂性并提高了代码的可读性。

Syntax:
<Acees_Modifier> interface <Interface_Name> {
 <Method_Signatures>;
}

Example:
package tech.besthub;
public interface Area {
 public void Square();
 public void Circle();
 public void Rectangle();
 public void Triangle();
}
//Class
package tech.besthub;
import java.util.Scanner;
public class shapeArea implements Area {
 public void Circle() {
  Scanner kb = new Scanner(System.in);
  System.out.println("Enter the radius of the circle");
  double r = kb.nextInt();
  double areaOfCircle = 3.142 * r * r;
  System.out.println("Area of the circle is" + areaOfCircle);
 }

 @Override
 public void Square() {
  // TODO Auto-generated method stub
  Scanner kb2 = new Scanner(System.in);
  System.out.println("Input the length of the side of the square");
  double s = kb2.nextInt();
  double areaOfSquare = s * s;
  System.out.println("Area of the square is" + areaOfSquare);
 }

 @Override
 public void Rectangle() {
  // TODO Auto-generated method stub
  Scanner kb3 = new Scanner(System.in);
  System.out.println("Enter the length of the Rectangle");
  double l = kb3.nextInt();
  System.out.println("Enter the breadth of the Rectangle");
  double b = kb3.nextInt();
  double areaOfRectangle = l * b;
  System.out.println("Area of the Rectangle is" + areaOfRectangle);
 }

 @Override
 public void Triangle() {
  // TODO Auto-generated method stub
  Scanner kb4 = new Scanner(System.in);
  System.out.println("Enter the base of the Triangle");
  double base = kb4.nextInt();
  System.out.println("Enter the height of the Triangle");
  double h = kb4.nextInt();
  double areaOfTriangle = 0.5 * base * h;
  System.out.println("Area of the Triangle is" + areaOfTriangle);
 }

 public static void main(String[] args) {
  shapeArea geometry = new shapeArea();
  geometry.Circle();
  geometry.Square();
  geometry.Rectangle();
  geometry.Triangle();
 }
}

Java中的抽象类

abstract-classes

抽象类几乎与接口相同,但不同之处在于,抽象类可以合并数据成员及其方法定义。

Syntax:
<Access_Modifier> abstract class <Name_of_the_class> {
 <Data Members>;
 <Data Methods>;
}

Example:
package tech.besthub;
public abstract class Person {
 private String Name;
 private String Gender;
 public Person(String nm, String Gen) {
  this.Name = nm;
  this.Gender = Gen;
 }

 public abstract void work();
 
 @Override
 public String toString() {
  return "Name=" + this.Name + "::Gender=" + this.Gender;
 }

 public void changeName(String newName) {
  this.Name = newName;

 }

 public void Exam() {
  // TODO Auto-generated method stub
 }
}

Class
package abstraction;
public class Employee extends Person {
 private int EmpId;
 public Employee(String EmployeeName, String Gen, int EmployeeID) {
  super(EmployeeName, Gen);
  this.EmpId = EmployeeID;
 }

 @Override
 public void Office() {
  if (EmpId == 0) {
   System.out.println("Employee Logged Out");
  } else {
   System.out.println("Employee Logged In");
  }
 }

 public static void main(String args[]) {
  Person employee = new Employee("Pavithra", "Female", 1094826);
  employee.Office();
  employee.changeName("Pavithra Tripathy");
  System.out.println(employee.toString());
 }
}

Java 面向对象概念中的封装

encapsulation

封装是在用户定义的类中将数据成员和数据方法绑定在一起的过程,该类应声明为私有。

Syntax:
<Access_Modifier> class <Class_Name> {
 private <Data_Members>;
 private <Data_Methods>;
}

Example:
package tech.besthub;
public class emp {
 public static void main(String[] args) {
  encapsule emp = new encapsule();
  emp.setName("Robert");
  System.out.println(emp.Name());
 }
}

package tech.besthub;
public class encapsule {
 private String empName;
 public String Name() {
  return empName;
 }

 public void setName(String empName) {
  this.empName = empName;
 }
}

Java面向对象概念中的继承

继承是简化软件开发的面向对象编程方法之一。它支持通过继承数据成员和方法以及先前定义的类的属性来构建新类。

继承类称为子类/派生类,继承类称为父类/基类。继承父类/基类的过程以不同的方式进行。我们现在将详细讨论其中的每一个。

继承类型

Single

single

单一继承由一个父类和一个子类组成。在这里,子类继承父类方法和数据成员。

Example:
package inheritance;
class Student {
 void Play() {
  System.out.println("Playing Football...");
 }
}

class Bob extends Student {
 void Study() {
  System.out.println("Studying Physics...");
 }
}

public class Single {
 public static void main(String args[]) {
  Bob d = new Bob();
  d.Study();
  d.Play();
 }
}

Multi-Level

multi

多级继承也是父子继承关系,但不同的是另一个子类继承了子类。

Example: 
package inheritance;
class Bike {
 public Bike() {
  System.out.println("Segment: 1000cc");
 }

 public void BikeType() {
  System.out.println("Bike Type: Sports");
 }
}

class NinJa extends Bike {
 public NinJa()
    {
  System.out.println("Make NinJa");
    }

 public void brand() {
  System.out.println("Manufacturer: Kawasaki");
 }

 public void speed() {
  System.out.println("Max Speed: 290Kmph");
 }
}

public class NinJa1000R extends NinJa {
 public NinJa1000R() {
  System.out.println("NinJa Model: 1000R");
 }

 public void speed() {
  System.out.println("Max Speed: 280Kmph");
 }

 public static void main(String args[]) {
  NinJa1000R obj = new NinJa1000R();
  obj.BikeType();
  obj.brand();
  obj.speed();
 }
}

Multiple

multiple

Java不支持多重继承,因为它最终会产生严重的二义性。

接口解决了钻石问题。

Hierarchical 

hierchalical

层次继承是一种父子关系。唯一的区别是多个子类继承一个父类。

Example:
package inheritance;
class Employee {
 double leaves = 25.00;
}

class PEmployee extends Employee {
 float totalHoursPerDay = (float) 8.00;
}

class TEmployee extends Employee {
 float totalHoursPerDay = (float) 10.50;
}

public class EmployeeSalary {
 public static void main(String args[]) {
  PEmployee permenant = new PEmployee();
  TEmployee temporary = new TEmployee();
  System.out.println("Permanent Employee Total Number of leaves are :\n" + permanent.leaves);
  System.out.println("Number of working hours for Permanent Employee are:\n" + permenant.totalHoursPerDay);
  System.out.println("Temporary Employee Total Number of leaves are :\n" + temporary.leaves);
  System.out.println("Number of working hours for Temporary Employee are :\n" + temporary.totalHoursPerDay);
 }
}

Hybrid

hybrid

混合继承可以是Java支持的三种继承类型中的任何一种组合。

package inheritance;
class C {
 public void Print() {
  System.out.println("C is the Parent Class to all A,B,D");
 }
}

class A extends C {
 public void Print() {
  System.out.println("A has Single Inheritance with C and shares Hierarchy with B");
 }
}

class B extends C {
 public void Print() {
  System.out.println("B has Single Inheritance with C and shares Hierarchy with A");
 }
}

public class D extends A {
 public void Print() {
  System.out.println("D has Single Inheritance with A and Multi-Level inheritance with C");
 }

 public static void main(String args[]) {
  A w = new A();
  B x = new B();
  C y = new C();
  D z = new D();
  y.Print();
  w.Print();
  x.Print();
  z.Print();
 }
}

Has-A Relation

当一个类从另一个类或其类的实例继承一个实例时,则该关系是Has-A类型。

Example: Orange HAS-A citrus taste.
package inheritance;
class School {
 private String name;
 School(String name) {
  this.name = name;
 }

 public String SchoolName() {
  return this.name;
 }
}

class Student {
 private String name;
 Student(String name) {
  this.name = name;
 }

 public String StudentName() {
  return this.name;
 }
}

public class HasARelation {
 public static void main(String[] args) {
  School schl = new School("St.John's School");
  Student candidate = new Student("Tobey Marshall");
  System.out.println(candidate.StudentName() + " is an Ex-Student of " + schl.SchoolName());
 }
}

Is-A Relation

is-a

当一个类从不同的类继承方法和成员时,这种关系被称为IS-A关系。

Example: Orange IS-A Fruit. 
package inheritance;
import java.util.*;
class Customer {
 public String Name;
 public String City;
 Customer(String Name, String City) {
  this.Name = Name;
  this.City = City;
 }
}

class Bank {
 private final List<Customer> customers;
 Bank(List<Customer> customers) {
  this.customers = customers;
 }

 public List<Customer> TotalAccountsInBank() {
  return customers;
 }
}

public class IsARelation {
 public static void main(String[] args) {
  Customer C1 = new Customer("Raju", "Bangalore");
  Customer C2 = new Customer("Shiva", "Hyderabad");
  Customer C3 = new Customer("Sachin", "Mumbai");
  Customer C4 = new Customer("Prashanth", "Vizag");
  Customer C5 = new Customer("John", "Goa");
  List<Customer> Customers = new ArrayList<Customer>();
  Customers.add(C1);
  Customers.add(C2);
  Customers.add(C3);
  Customers.add(C4);
  Customers.add(C5);
  Bank ABCBank = new Bank(Customers);
  List<Customer> cust = ABCBank.TotalAccountsInBank();
  for (Customer cst : cust) {
   System.out.println("Name of the Customer : " + cst.Name + "\n" + "City : " + cst.City);
  }
 }
}

Java面向对象概念中的多态 

多态是一种Java编程语言能力,用于根据使用的数据类型和实现它们的类以多种方式处理对象、运算符和方法。许多编程概念解释了Java中的多态过程。

重载 

overloading

当一个类有两个或多个同名的方法,但根据声明的参数数量选择特定的方法时,就会实现方法重载的过程。

Example:
package polymorphism;
public class Addition {
 public int add(int x, int y) {
  return (x + y);
 }

 public double add(double d, double e, double f, double g) {
  return (d + e + f + g);
 }

 public double add(double a, double b) {
  return (a + b);
 }

 public static void main(String args[]) {
  Addition a = new Addition();
  System.out.println(a.add(25, 30));
  System.out.println(a.add(10.0, 15.0, 20.0, 25.0));
  System.out.println(a.add(127.5, 123.5));
 }
}

重写

/overriding

方法重写是允许子类实现父类中存在的特定类的过程。

Example:
package polymorphism;
public class SuperKeyWord {
 public static void main(String[] args) {
  triangle two = new triangle();
  two.countsides();
 }
}

class square {
 int sides = 4;
}

class triangle extends square {
 int sides = 3;
 public void countsides() {
  System.out.println("Number of sides in square : " + sides);
  System.out.println("Number of sides in triangle : " + super.sides);
 }
}

运算符重载和运算符重写

Java不支持操作符重载,也不支持操作符重载。Java编程语言的设计者了解C++编程语言中操作符重载和操作符重写的歧义。因此,为了避免复杂性,他们选择不包括操作符重载和操作符重写。

静态多态性

静态多态/编译时多态在编译阶段执行。这里,重载方法是在编译阶段解决的。

动态多态性

动态多态性/运行时多态性在程序执行阶段处理。这里,重写方法在执行阶段被解析。

超级关键字

The term "super" is a predefined keyword in Java that refers to the immediate parent class object or method defined in the program. In this procedure, whenever you create an instance of a subclass, then an instance of the parent class is also automatically created. The super reference variable will implicitly refer to that.

Example:
package polymorphism;
public class SuperKeyWord {
 public static void main(String[] args) {
  triangle two = new triangle();
  two.countsides();
 }
}

class square {
 int sides = 4;
}

class triangle extends square {
 int sides = 3;
 public void countsides() {
  System.out.println("Number of sides in square : " + sides);
  System.out.println("Number of sides in triangle : " + super.sides);
 }
}

Java 面向对象概念中的访问修饰符

access-mod

在面向对象编程中,该语言基于定义的访问说明符提供对对象、方法和数据成员的可访问性。同样,在Java编程语言中,我们有四个不同的访问说明符。

Default

如果程序员没有提供访问说明符,编译器将考虑默认访问说明符。在Java中,默认访问是PUBLIC。但是,此访问权限仅限于用户正在处理的当前包。以下是一个可视化编码示例,有助于阐明此过程:

Example:
package abc;
public class Sum {
 int add(int x, int y) {
  return x + y;
 }
}

  
  

package xyz;
import abc.Sum;
public class Access {
   public static void main(String args[]){
 Sum obj = new Sum();
 obj.add(67, 129);
   }
}

Public

公共访问说明符提供对数据成员、方法和对象的通用访问。

考虑到相同的示例,如果我们只将可见性更改为对公共添加(),我们就可以执行它,而不会出现任何错误。

Example:
package abc;
public class Sum {
 public int add(int x, int y) {
  return x + y;
 }
}

package xyz;
import abc.*;
public class Access {
 public static void main(String args[]) {
  Sum s = new Sum();
  System.out.println(s.add(67, 129));
 }
}

Protected

如果试图访问数据成员、方法和对象的子类位于定义受保护数据的同一个包中,则受保护访问说明符提供对这些数据成员、方法和对象的访问。否则,外部类应该扩展受保护类,否则它们将不可访问。

Example:
package abc;
public class Sum {
 protected int add(int x, int y) {
  return x + y;
 }
}

package xyz;
import abc.*;
class Access extends Sum {
 public static void main(String args[]) {
  Access obj = new Access();
  System.out.println(obj.add(323, 223));
 }
}

Private

对私有说明符的访问将变量和方法的访问严格限制为只能访问在其中声明它们的类。除此之外,用户无法访问它们。

Example:
package xyz;
class Parent {
 private double x = 25;
 private int cube(int p) {
  return p * p * p;
 }
}

public class Access {
 public static void main(String args[]) {
  Parent object = new Parent();
  System.out.println(object.x);
  System.out.println(object.cube(10));
 }
}

Java面向对象概念中的方法调用

Java只支持按值调用。在这里,我们将值传递给特定的方法,然后在该方法的隐含之后,我们得到预期的结果。

For example:
package xyz;
public class Value {
 public static void main(String[] args) {
  int num = 25;
  change(num);
  System.out.println(num);
 }

 public static void change(int num) {
  num = 100;
 }
}

结论

我们希望这篇关于Java中面向对象概念的综合教程将帮助您理解这部分超普及编程语言的基础知识。