面向对象:以类的方式组织代码,以对象组织数据
特性:
类:抽象概念
对象:具体事物
使用new实例化一个对象,如
Student student = new Student();//实例化对象
new时:
构造器在实例化时首先被自动调用,用于初始化参数。
new的本质是调用了构造器,返回一个对象
名字和类名相同
没有返回类型(不能写!)
可以传参
this是一个指针,指向这个对象本身
public class Person {
String name;
public Person(){
//构造器
this.name = "小明";
}
}
“高耦合,低内聚”,内部数据操作细节自己完成,不由外部干涉, 暴露少部分方法给外部使用。
封装:禁止访问对象的实际表示,而应该通过接口来访问。
修饰词:

使用extend关键字,表示子类是父类的扩展
public class Student extends Person{
Student(String name){
this.name = name;
}
}
使用super可以访问到父类,构造器中super.generator()可以调用父类的构造器。
public class Person {
String name;
public Person(String name){
//构造器
this.name = name;
}
}
public class Student extends Person{
Student(String name){
super(name);
}
}
public class Demo2 {
public static void main(String[] args){
Student s = new Student("小明");
System.out.println(s.name);
}
}
输出“小明”。
如果在子类中不指定调用super,会自动调用
public class Person {
String name;
public Person() {
//构造器
System.out.println("父类Person无参数构造器执行");
}
}
public class Student extends Person{
Student(){
System.out.println("子类Student无参数构造器执行");
}
}
在new Student时输出:

若将子类构造器改为有参,仍然会首先调用父类的无参构造器

大致逻辑如下:

注:
public static void test(){
System.out.println("Person Test");
}
Student类:
public static void test(){
System.out.println("Student Test");
}
调用:
public static void main(String[] args){
Student s = new Student("小明");
s.test();
}
结果:

public static void main(String[] args){
Person s = new Student("小明");
s.test();
}
会导致输出:

这可以说明
以上结论来自于静态方法
如果全部改为非静态,即将test改为无static修饰
如
@Override
public void test(){
System.out.println("Student Test");
}
注意点:
同一方法根据对象的不同采用不同的行为
一个对象的实际类型是确定的,但引用类型并不一致
如
Student s = new Student();
Person s1 = new Student();
Object s2 = new Student();
实际类型都是Student,而引用类型可以是其任意父类
对于这样的对象s1/s2,如果没有static修饰,调用一个方法时
若子类父类都有该方法,且子类未重写:调用父类的方法
若都有,但子类重写了:调用子类的方法
若只有子类有,则无法调用(需要强制类型转换修改引用类型)
如在Student写一个新的eat方法:

即能调用的方法取决于其引用类型而不是实际类型
static 属于类,不属于对象,不可重写
final 无法修改,不可重写
private 只属于父类,无法重写
语法:
obj instanceof class
System.out.println(s instanceof Student);//true
System.out.println(s1 instanceof Student);//true
System.out.println(s1 instanceof Object);//true
System.out.println(s2 instanceof Student);//true
System.out.println(s2 instanceof Teacher);//false
如果对象的类是class或class的子类,则为True
在编译状态中,class可以是object对象的父类,自身类,子类。在这三种情况下Java编译时不会报错。(需要在同一条继承链上)
在运行转态中,class可以是object对象的父类,自身类,不能是子类。在前两种情况下result的结果为true,最后一种为false。但是class为子类时编译不会报错。运行结果为false。
编译的时候查看其引用类型判断是否报错。
运行的时候查看其实际类型判断是否为true。
优先级:父类>子类。
子类转父类自动转换。
父类转子类需要强制转换。
转父类后部分方法可能无法再调用。
static修饰(静态)的从属于类,普通的从属于对象
静态方法不能调用非静态成员

无static修饰的变量
每创建一个实例就会生成一个新的内存空间
类内部只有非静态方法可以访问实例变量
静态方法或其他类中只能通过实例对象访问

abstract修饰
public abstract class Shape {
public int width; // 几何图形的长
public int height; // 几何图形的宽
public Shape(int width, int height) {
this.width = width;
this.height = height;
}
public abstract double area(); // 定义抽象方法,计算面积
}
public class Square extends Shape {
public Square(int width, int height) {
super(width, height);
}
// 重写父类中的抽象方法,实现计算正方形面积的功能
@Override
public double area() {
return width * height;
}
}
public class Triangle extends Shape {
public Triangle(int width, int height) {
super(width, height);
}
// 重写父类中的抽象方法,实现计算三角形面积的功能
@Override
public double area() {
return 0.5 * width * height;
}
}
[public] interface interface_name [extends interface1_name[, interface2_name,…]] {
// 接口体,其中可以包含定义常量和声明方法
[public] [static] [final] type constant_name = value; // 定义常量
[public] [abstract] returnType method_name(parameter_list); // 声明方法
}
一个类可以实现一个或者多个接口
实现使用implements关键字
<public> class <class_name> [extends superclass_name] [implements interface1_name[, interface2_name…]] {
// 主体
}
与继承类似,可以获得所有的常量和方法
implements在extend后
类实现接口后必须重写所有抽象方法
public interface IMath {
public int sum(); // 完成两个数的相加
public int maxNum(int a,int b); // 获取较大的数
}
public class MathClass implements IMath {
private int num1; // 第 1 个操作数
private int num2; // 第 2 个操作数
public MathClass(int num1,int num2) {
// 构造方法
this.num1 = num1;
this.num2 = num2;
}
// 实现接口中的求和方法
public int sum() {
return num1 + num2;
}
// 实现接口中的获取较大数的方法
public int maxNum(int a,int b) {
if(a >= b) {
return a;
} else {
return b;
}
}
}
类内部定义的类
分类:

Outer o = new Outer();
//外部类可直接new
Inner in = new Inner();
//外部类外需要通过外部类来实例化内部类
Outer.Inner inner = o.new Inner();
没有static修饰,也成为非静态内部类,例:
public class Outer {
class Inner {
// 实例内部类
}
}
static修饰的内部类,例:
public class Outer {
static class Inner {
// 静态内部类
}
}
一个方法中定义的类,如:
public class Test {
public void method() {
class Inner {
// 局部内部类
}
}
}
没有类名的内部类,直接使用new来声明,例:
new <类或接口>() {
// 类的主体
};
一般用法:
public class Out {
void show() {
System.out.println("调用 Out 类的 show() 方法");
}
}
public class TestAnonymousInterClass {
// 在这个方法中构造一个匿名内部类
private void show() {
Out anonyInter = new Out() {
// 获取匿名内部类的实例
void show() {
System.out.println("调用匿名类中的 show() 方法");
}
};
anonyInter.show();
}
public static void main(String[] args) {
TestAnonymousInterClass test = new TestAnonymousInterClass();
test.show();
}
}
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的rubyyaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir
假设我有一个FireNinja我的数据库中的对象,使用单表继承存储。后来才知道他真的是WaterNinja.将他更改为不同的子类的最干净的方法是什么?更好的是,我很想创建一个新的WaterNinja对象并替换旧的FireNinja在数据库中,保留ID。编辑我知道如何创建新的WaterNinja来self现有FireNinja的对象,我也知道我可以删除旧的并保存新的。我想做的是改变现有项目的类别。我是通过创建一个新对象并执行一些ActiveRecord魔法来替换行,还是通过对对象本身做一些疯狂的事情,或者甚至通过删除它并使用相同的ID重新插入来做到这一点,这是问题的一部分。